JavaScript Iterate JSON Array | Example code

  • by

Use for loop and length method to Iterate JSON Array in JavaScript. You can also use forEach if you want a access property and value of object.

JavaScript Iterate JSON Array

Simple example code loop over the Array like this:

<!DOCTYPE html>
<html>
<body>

  <script>
    var json = [{
      "id" : "1", 
      "msg"   : "Hello",
      "tid" : "2013-05-05 23:35",
      "fromWho": "[email protected]"
    },
    {
      "id" : "2", 
      "msg"   : "Bye",
      "tid" : "2013-05-05 23:45",
      "fromWho": "[email protected]"
    }];
    for(var i = 0; i < json.length; i++) {
      var obj = json[i];

      console.log(obj.id);
    }

  </script>

</body>
</html> 

Output:

JavaScript Iterate JSON Array

Or use forEach

var json = [{
    "id" : "1", 
    "msg"   : "hi",
    "tid" : "2013-05-05 23:35",
    "fromWho": "[email protected]"
},
{
    "id" : "2", 
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "[email protected]"
}];

json.forEach((item) => {
  console.log('ID: ' + item.id);
  console.log('MSG: ' + item.msg);
  console.log('TID: ' + item.tid);
  console.log('FROMWHO: ' + item.fromWho);
});

Output:

ID: 1 code.html:20:11
MSG: hi code.html:21:11
TID: 2013-05-05 23:35 code.html:22:11
FROMWHO: [email protected] code.html:23:11

ID: 2 code.html:20:11
MSG: there code.html:21:11
TID: 2013-05-05 23:45 code.html:22:11
FROMWHO: [email protected]

To get Output into a HMTL web page use this code.

<!DOCTYPE html>
<html>
<body>

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

</body>
</html> 

Do comment if you have any doubts or suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.