traverse object javascript 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: js loop over object
const object = {a: 1, b: 2, c: 3};
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
Example 3: object traversal javascript
for (var prop in obj) {
obj[prop] = 'xxx';
}