Skip to content

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": "Hello@email.se"
    },
    {
      "id" : "2", 
      "msg"   : "Bye",
      "tid" : "2013-05-05 23:45",
      "fromWho": "Bye@email.se"
    }];
    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": "hello1@email.se"
},
{
    "id" : "2", 
    "msg"   : "there",
    "tid" : "2013-05-05 23:45",
    "fromWho": "hello2@email.se"
}];

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: hello1@email.se 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: hello2@email.se

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. Required fields are marked *

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