how to traverse an object in javascript code example
Example 1: javascript iterate over object
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
Example 2: iterate over object javascript
const keys = Object.keys(fruits)
for (const key of keys) {
console.log(key)
}
Example 3: javascript iterate object
let person={
first_name:"johnny",
last_name: "johnson",
phone:"703-3424-1111"
};
for (let i in person) {
let t = person[i]
console.log(i,":",t);
}
Example 4: js loop through object
const obj = { a: 1, b: 2 };
Object.keys(obj).forEach(key => {
console.log("key: ", key);
console.log("Value: ", obj[key]);
} );
Example 5: javascript iterate object key values
Object.entries(obj).forEach(([key, value]) => {
console.log(key, value);
});
Example 6: javascript loop through object
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}