javascript foreach loop array of objects code example

Example 1: iterate array javascript

array = [ 1, 2, 3, 4, 5, 6 ]; 
for (index = 0; index < array.length; index++) { 
    console.log(array[index]); 
}

Example 2: javascript loop through array of objects

let arr = [object0, object1, object2];

for (let elm of arr) {
  console.log(elm);
}

Example 3: 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 4: javascript foreach call specific value in array

run.addEventListener("click", function () {
    people.forEach((element) => console.log(element.firstname));
  }); // select a specific string in array

Example 5: 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”