Hello, I have the following JSON structure:
[ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];
how to iterate over it using jquery or javascript?
Hello, I have the following JSON structure:
[ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];
how to iterate over it using jquery or javascript?
Taken from jQuery docs (http://docs.jquery.com/Utilities/jQuery.each):
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
mootools example:
var ret = JSON.decode(jsonstr);
ret.each(function(item){
alert(item.id+'_'+item.classd);
});
You can use a mini library like objx - http://objx.googlecode.com/
You can write code like this:
var data = [ {"id":"10", "class": "child-of-9"},
{"id":"11", "class": "child-of-10"}];
// alert all IDs
objx(data).each(function(item) { alert(item.id) });
// get all IDs into a new array
var ids = objx(data).collect("id").obj();
// group by class
var grouped = objx(data).group(function(item){ return item.class; }).obj()
There are more 'plugins' available to let you handle data like this, see http://code.google.com/p/objx-plugins/wiki/PluginLibrary
var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "classd": "child-of-10"}];
for(var i=0;i<arr.length;i++){
var obj = arr[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
}
}
note: the foreach method is cool for simple objects. Not very smart to use with DOM object.