foreach objects 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: foreach object javascript
const games = {
"Fifa": "232",
"Minecraft": "476"
"Call of Duty": "182"
};
Object.keys(games).forEach((item, index, array) => {
let msg = `There is a game called ${item} and it has sold ${games[item]} million copies.`;
console.log(msg);
});
Example 3: javascript foreach object
function logArrayElements(element, index, array) {
console.log('a[' + index + '] = ' + element)
}
[2, 5, , 9].forEach(logArrayElements)