Skip to content

JavaScript Iterate JSON Array | Example code

  • by

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

const jsonArray = [
  { name: 'John', age: 25 },
  { name: 'Jane', age: 30 },
  { name: 'Bob', age: 35 }
];

// Using a for loop
for (let i = 0; i < jsonArray.length; i++) {
  const item = jsonArray[i];
  console.log(item.name, item.age);
}

// Using forEach method
jsonArray.forEach(item => {
  console.log(item.name, item.age);
});

// Using map method
const mappedArray = jsonArray.map(item => {
  return item.name + ' is ' + item.age + ' years old';
});
console.log(mappedArray);

// Using for...of loop
for (const item of jsonArray) {
  console.log(item.name, item.age);
}

You can use a for loop or any array iteration method such as forEach, map, or for...of.

JavaScript Iterate JSON Array

A simple example code loop over the Array is 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> 

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading