js iterate through array of objects code example

Example 1: javascript loop through array of objects

var people=[
  {first_name:"john",last_name:"doe"},
  {first_name:"mary",last_name:"beth"}
];
for (let i = 0; i < people.length; i++) { 
  console.log(people[i].first_name);
}

Example 2: loop array of objects

const myArray = [{x:100}, {x:200}, {x:300}];

myArray.forEach((element, index, array) => {
    console.log(element.x); // 100, 200, 300
    console.log(index); // 0, 1, 2
    console.log(array); // same myArray object 3 times
});

Example 3: how to get value in array object value using for loop in javascript

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => element.x);
console.log(newArray); // [100, 200, 300]

Example 4: looping through an object of objects with arrays

let storeItems = {   
    eggs: {
      price: 3.77, quantity: 30
    },   
                  
    milk: {
      price: 2.22, quantity: 23
    },   
                   
    butter: {
      price: 2.00, quantity: 22
    },       
                   
    carrots: {
      price: 3.00, quantity: 11
    },   
                   
    beef: {
      price: 6.18, quantity: 34
    },   
    chicken: {
      price: 5.44, quantity: 34
    }
  };
  
  for(let item in storeItems) {   
    console.log(`${storeItems[item].quantity} ${item}s each cost ${storeItems[item].price}`);
}
  
  
// //OUTPUT:30 eggs each cost 3.77//23 milks each cost 2.22//22 butters each cost 2//11 carrots each cost 3//34 beefs each cost 6.18//34 chickens each cost 5.44