Advertisement
Advertisement


How do I iterate over a JSON structure?


Question

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?

2019/05/31
1
527
5/31/2019 9:08:58 PM

Accepted Answer

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));
});
2017/08/02
441
8/2/2017 10:13:33 AM


Use for...of:

<html>
<body>
<script type="text/javascript">

  var mycars = [{name:'Susita'}, {name:'BMW'}];

  for (var car of mycars) 
  {
    document.write(car.name + "<br />");
  }

</script>
</body>
</html>

Will result in:

Susita
BMW
2020/01/30

Please let me know if it is not easy:

var jsonObject = {
  name: 'Amit Kumar',
  Age: '27'
};

for (var prop in jsonObject) {
  alert("Key:" + prop);
  alert("Value:" + jsonObject[prop]);
}
2019/05/13

If this is your dataArray:

var dataArray = [{"id":28,"class":"Sweden"}, {"id":56,"class":"USA"}, {"id":89,"class":"England"}];

then:

$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {  
         var ID = this.id;
         var CLASS = this.class;
});
2016/11/22

mootools example:

var ret = JSON.decode(jsonstr);

ret.each(function(item){
    alert(item.id+'_'+item.classd);
});
2009/07/03

Copied and pasted from http://www.w3schools.com, there is no need for the JQuery overhead.

var person = {fname:"John", lname:"Doe", age:25};

var text = "";
var x;
for (x in person) {
    text += person[x];
}

RESULT: John Doe 25

2016/05/09