javascript iterate over object code example
Example 1: javascript loop through object
Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);
Example 2: javascript loop through object
// object to loop through
let obj = { first: "John", last: "Doe" };
// loop through object and log each key and value pair
//ECMAScript 5
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
//ECMAScript 6
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}
//ECMAScript 8
Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);
// OUTPUT
/*
first John
last Doe
*/
Example 3: loop through object javascript
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
// for-in
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
// for-of with Object.keys()
for (var key of Object.keys(p)) {
console.log(key + " -> " + p[key])
}
// Object.entries()
for (let [key, value] of Object.entries(p)) {
console.log(`${key}: ${value}`);
}
Example 4: javascript iterate over object
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
Example 5: javascript iterate over object
var person={
first_name:"johnny",
last_name: "johnson",
phone:"703-3424-1111"
};
for (var property in person) {
console.log(property,":",person[property]);
}
Example 6: javascript iterate over object
for (variable in object)
statement