loop through object array in javascript 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 object array iteration
let obj = {
key1: "value1",
key2: "value2",
key3: "value3"
}
Object.keys(obj).forEach(key => {
let value = obj[key];
});
Example 3: javascript loop through object properties
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
}
}
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}`);
}
Example 5: how to loop through an array of objects+
var arr = [[1,2], [3,4], [5,6]];
for (var i=0; i < arr.length; i++) {
for (var j=0; j < arr[i].length; j++) {
console.log(arr[i][j]);
}
}