Flueras Bogdan Flueras Bogdan - 7 months ago 10
Javascript Question

How do I iterate over a JSON structure?

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 jQuery or JavaScript?

Answer

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));
});