Skip to content

JavaScript loop through array of objects | Example code

  • by

You can loop through an array of objects using forEach() outer loop to iterate through the objects array and then use the for...in loop to iterate through the properties of an individual object in JavaScript.

JavaScript loop through array of objects

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script >
    const mobiles = [
    {
      brand: 'Samsung',
      model: 'Galaxy Note 11'
    },
    {
      brand: 'Google',
      model: 'Pixel 4'
    },
    {
      brand: 'Apple',
      model: 'iPhone 13'
    }
    ];

    mobiles.forEach(mobile => {
      for (let key in mobile) {
        console.log(`${key}: ${mobile[key]}`);
      }
    });
  </script>
</body>
</html>

Output:

JavaScript loop through array of objects

Loop through an array of objects and get all object values as a single string using a map and join methods.

const arr = [
  { id: 1, value: "Apple" },
  { id: 1, value: "Orange" },
  { id: 1, value: "Pine Apple" },
  { id: 1, value: "Banana" },
];
const result = arr.map(({ value }) => value).join(', ')
console.log(result)

Output: Apple, Orange, Pine Apple, Banana

Using Array.prototype.forEach() function

var obj = [
    { name: 'Max', age: 23 },
    { name: 'John', age: 20 },
    { name: 'Caley', age: 18 }
];
 
obj.forEach(o => console.log(o));

Using for…of statement

var obj = [
    { name: 'Max', age: 23 },
    { name: 'John', age: 20 },
    { name: 'Caley', age: 18 }
];
 
for (var value of obj) {
    console.log(value)
}

Using Object.entries() function

var obj = [
    { name: 'Max', age: 23 },
    { name: 'John', age: 20 },
    { name: 'Caley', age: 18 }
];
 
Object.entries(obj).forEach(([_, value]) => console.log(value));

Do comment if you have any doubts or suggestions on this JS Object code.

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