foreach with object code example
Example 1: foreach object javascript
const students = {
adam: {age: 20},
kevin: {age: 22},
};
Object.entries(students).forEach(student => {
console.log(`Student: ${student[0]} is ${student[1].age} years old`);
});
Example 2: javascript foreach object
const list = {
key: "value",
name: "lauren",
email: "[email protected]",
age: 30
};
Object.keys(list).forEach(val => {
let key = val;
let value = list[val];
console.log(`${key} : ${value}`);
});
Example 3: foreach object javascript
Add thisvar p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
Example 4: javascript foreach in object
for (var key in validation_messages) {
if (!validation_messages.hasOwnProperty(key)) continue;
var obj = validation_messages[key];
for (var prop in obj) {
if (!obj.hasOwnProperty(prop)) continue;
alert(prop + " = " + obj[prop]);
}
}