Skip to content

Looping JSON Array in JavaScript | Example code

  • by

You can use for loop or foreach loop to Looping JSON Array in JavaScript. Using for..in to iterate through arrays generally isn’t a great idea in JS.

Looping JSON Array in JavaScript

Simple example code JavaScript to loop through JSON array using for loop.

<!DOCTYPE html>
<html>
<body>

  <script>
   var json = [{
    "id" : "1", 
    "msg"   : "ABC",
    "tid" : "2013-05-05 23:35",
    "fromWho": "[email protected]"
  },
  {
    "id" : "2", 
    "msg"   : "XYZ",
    "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, obj.msg, obj.fromWho);
  }
</script>

</body>
</html> 

Output:

Looping JSON Array in JavaScript

Using for-each loop

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

If you want to output in the HTML page

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

Do comment if you have any doubts or suggestions on this JS JSON 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 *