looping through an array of objects code example

Example 1: javascript loop through object example

var person={
 	first_name:"johnny",
  	last_name: "johnson",
	phone:"703-3424-1111"
};
for (var property in person) {
  	console.log(property,":",person[property]);
}

Example 2: 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 3: ho to loop trough an array of objects

yourArray.forEach(function (arrayItem) {
    var x = arrayItem.prop1 + 2;
    console.log(x);
});

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”

Example 5: iterate over array of objects javascript

// Find an element in an array

const people = [ {name: "john", age:23},
                {name: "john", age:43},
                {name: "jim", age:101},
                {name: "bob", age:67} ];

const john = people.find(person => person.name === 'john');
console.log(john);

Example 6: loop array of objects

const people = [
    {name: 'John', age: 23}, 
    {name: 'Andrew', age: 3}, 
    {name: 'Peter', age: 8}, 
    {name: 'Hanna', age: 14}, 
    {name: 'Adam', age: 37}];

const anyAdult = people.some(person => person.age >= 18);
console.log(anyAdult); // true