how can foreach in the object in js code example
Example 1: foreach object javascript
const students = {
adam: {age: 20},
kevin: {age: 22},
};
Object.entries(students).forEach(student => {
// key: student[0]
// value: student[1]
console.log(`Student: ${student[0]} is ${student[1].age} years old`);
});
/* Output:
Student: adam is 20 years old
Student: kevin is 22 years old
*/
Example 2: foreach object javascript
const obj = {
name: 'Jean-Luc Picard',
rank: 'Captain'
};
// Prints "name Jean-Luc Picard" followed by "rank Captain"
Object.entries(obj).forEach(entry => {
const [key, value] = entry;
console.log(key, value);
});