JavaScript Examples: iterate over object
// Example JavaScript code to demonstrate different ways to iterate over an object's key-value pairs
// Define an object with some key-value pairs
const person = {
name: "Alice",
age: 30,
occupation: "Engineer"
};
// Using for...in loop to iterate over the object's keys
console.log("Using for...in loop:");
for (const key in person) {
if (person.hasOwnProperty(key)) { // Check if the property is directly on the object
console.log(`Key: ${key}, Value: ${person[key]}`);
}
}
// Using Object.keys() method to get an array of keys and forEach to iterate
console.log("\nUsing Object.keys() and forEach:");
Object.keys(person).forEach(key => {
console.log(`Key: ${key}, Value: ${person[key]}`);
});
// Using Object.values() method to get an array of values and forEach to iterate
console.log("\nUsing Object.values() and forEach:");
Object.values(person).forEach(value => {
console.log(`Value: ${value}`);
});
// Using Object.entries() method to get an array of [key, value] pairs and forEach to iterate
console.log("\nUsing Object.entries() and forEach:");
Object.entries(person).forEach(([key, value]) => {
console.log(`Key: ${key}, Value: ${value}`);
});
// Using for...of loop with Object.entries() to iterate over [key, value] pairs