In JavaScript, you can loop through an array of objects using the forEach()
method combined with the for...in
loop.
Consider the following code example that illustrates how to iterate over an array containing objects and print the properties of each object:
const mobiles = [
{
brand: 'Samsung',
model: 'Galaxy Note 9'
},
{
brand: 'Google',
model: 'Pixel 3'
},
{
brand: 'Apple',
model: 'iPhone X'
}
]
mobiles.forEach(mobile => {
for (let key in mobile) {
console.log(`${key}: ${mobile[key]}`)
}
})
When you execute the above code, you will see the following output:
brand: Samsung
model: Galaxy Note 9
brand: Google
model: Pixel 3
brand: Apple
model: iPhone X
In this code, the outer forEach()
loop is used to iterate through the array of objects. Inside this loop, the for...in
loop is used to iterate through the properties of each individual object.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.