for each element in object javascript 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 loop through object
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
Example 3: 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 4: foreach object js
const object1 = {
a: 'somestring',
b: 42
};
for (let [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`);
}
Example 5: for each element in object
var obj = {
first: "John",
last: "Doe"
};
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
Example 6: foreach object javascript
const obj = {
a: "aa",
b: "bb",
c: "cc",
};
for(let key in obj) {
console.log(key);
console.log(obj[key]);
}