I have my JSON as follows
{"DATA": [{"id":11,"name":"ajax","subject":"OR","mark":63}, {"id":12,"name":"javascript","subject":"OR","mark":63}, {"id":13,"name":"jquery","subject":"OR","mark":63}, {"id":14,"name":"ajax","subject":"OR","mark":63}, {"id":15,"name":"jquery","subject":"OR","mark":63}, {"id":16,"name":"ajax","subject":"OR","mark":63}, {"id":20,"name":"ajax","subject":"OR","mark":63}],"COUNT":"120"}
Is there any good method to find out the distinct name
from this JSON
Result javascript,jquery,ajax
I can do this using following methode
var arr=['']; var j=0; for (var i = 0; i < varjson.DATA.length; i++) { if($.inArray(varjson.DATA[i]["name"],arr)<0){ arr[j]=varjson.DATA[i]["name"]; j++; } }
Is there any better method
which gave me better performance?
JSON array can store multiple values. It can store string, number, boolean or object in JSON array. In JSON array, values must be separated by comma.
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).
I would use one Object and one Array, if you want to save some cycle:
var lookup = {}; var items = json.DATA; var result = []; for (var item, i = 0; item = items[i++];) { var name = item.name; if (!(name in lookup)) { lookup[name] = 1; result.push(name); } }
In this way you're basically avoiding the indexOf
/ inArray
call, and you will get an Array that can be iterate quicker than iterating object's properties – also because in the second case you need to check hasOwnProperty
.
Of course if you're fine with just an Object you can avoid the check and the result.push
at all, and in case get the array using Object.keys(lookup)
, but it won't be faster than that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With