How do I iterate over a JSON structure?

Flueras Bogdan picture Flueras Bogdan · Jul 3, 2009 · Viewed 927.8k times · Source

I have the following JSON structure:

[{ "id":"10", "class": "child-of-9" }, { "id": "11", "classd": "child-of-10" }]

How do I iterate over it using JavaScript?

Answer

Your Friend Ken picture Your Friend Ken · Jul 11, 2009
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];
    }
}

var arr = [ {"id":"10", "class": "child-of-9"}, {"id":"11", "class": "child-of-10"}];
    
for (var i = 0; i < arr.length; i++){
  document.write("<br><br>array index: " + i);
  var obj = arr[i];
  for (var key in obj){
    var value = obj[key];
    document.write("<br> - " + key + ": " + value);
  }
}

note: the for-in method is cool for simple objects. Not very smart to use with DOM object.