javascript foreach on 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: object foreach
const obj = {
name: 'Jean-Luc Picard',
rank: 'Captain'
};
Object.keys(obj).forEach(key => {
console.log(key, obj[key]);
});
Example 3: js loop array
let colors = ['red', 'green', 'blue'];
for (const color of colors){
console.log(color);
}
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: foreach object javascript
const obj = {
a: "aa",
b: "bb",
c: "cc",
};
for(let key in obj) {
console.log(key);
console.log(obj[key]);
}
Example 6: 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]);
}
}