How to Iterate Loop through JSON Array in JavaScript

Here are four ways to iterate a loop through a JSON array in JavaScript.

  1. Using for loop
  2. Using for…of loop
  3. Using forEach()
  4. Using a map() (especially if you want to transform the data)

Method 1: Using for loop

let jsonArray = [
  { "name": "AB", "age": 25 },
  { "name": "De", "age": 30 },
  { "name": "Villiers", "age": 35 }
];

for (let i = 0; i < jsonArray.length; i++) {
  console.log(jsonArray[i].name, jsonArray[i].age);
}

Output

AB 25
De 30
Villiers 35

Method 2: Using for…of loop

let jsonArray = [
  { "name": "AB", "age": 25 },
  { "name": "De", "age": 30 },
  { "name": "Villiers", "age": 35 }
];

for (let item of jsonArray) {
  console.log(item.name, item.age);
}

Output

AB 25
De 30
Villiers 35

Method 3: Using forEach()

let jsonArray = [
  { "name": "AB", "age": 25 },
  { "name": "De", "age": 30 },
  { "name": "Villiers", "age": 35 }
];

jsonArray.forEach(function (item) {
  console.log(item.name, item.age);
});

Output

AB 25
De 30
Villiers 35

Method 4: Using a map()

let jsonArray = [
  { "name": "AB", "age": 25 },
  { "name": "De", "age": 30 },
  { "name": "Villiers", "age": 35 }
];

jsonArray.map(function (item) {
  console.log(item.name, item.age);
  // You can return a transformed item here if needed
});

Output

AB 25
De 30
Villiers 35

Conclusion

To iterate each element of the json array without any additional control flow or transformation, you can use the “Array.forEach()” method.

If you are transforming each item in the array and need a new array, the map() is the way to go.

If you want more control over the loop or need to break out early, the traditional for loop or for…of loop would be better.

Related posts

How to Use async/await with a for loop in JavaScript

Leave a Comment