loop through array inside and object inside an object code example
Example 1: 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}`);
}
Example 2: iterate over array of objects javascript
const people = [
{ name: "John", age: 21 },
{ name: "Peter", age: 31 },
{ name: "Andrew", age: 29 },
{ name: "Thomas", age: 25 }
];
let sortByAge = people.sort(function (p1, p2) {
return p1.age - p2.age;
});
console.log(sortByAge);