How do I iterate over a JSON structure? [duplicate]
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.
Taken from jQuery docs:
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));});
Use for...of:
var mycars = [{name:'Susita'}, {name:'BMW'}];for (var car of mycars) { document.write(car.name + "<br />");}
Result:
SusitaBMW