In JavaScript, object iteration involves accessing its properties one by one to read, modify, or process their keys and values.
- for...in iterates over enumerable properties, including inherited ones.
- Object.entries() provides key-value pairs for easy iteration.
- Object.keys() with forEach() iterates over an object's own enumerable keys.
Approach 1: Using for...in Loop
The for...in loop iterates over the enumerable properties of an object. We use hasOwnProperty() to ensure that only the object's own properties are processed.
Example: Iterates over the object's keys and values.
function iterateObject() {
let exampleObj = {
book: "Sherlock Holmes",
author: "Arthur Conan Doyle",
genre: "Mystery"
};
for (let key in exampleObj) {
if (Object.prototype.hasOwnProperty.call(exampleObj, key)) {
let value = exampleObj[key];
console.log(key, value);
}
}
}
iterateObject();
Output
book Sherlock Holmes author Arthur Conan Doyle genre Mystery
Syntax:Â
for (let key in object) {
if (Object.prototype.hasOwnProperty.call(object, key)) {
console.log(key, object[key]);
}
}
Approach 2: Using Object.entries() and forEach()
The Object.entries() method returns an array containing the object's own enumerable key-value pairs. We can use forEach() to iterate over each pair, where the first element is the key and the second is the value.
Example: Iterates over each key-value pair using Object.entries().
function iterateObject() {
let exampleObj = {
book: "Sherlock Holmes",
author: "Arthur Conan Doyle",
genre: "Mystery"
};
Object.entries(exampleObj).forEach(([key, value]) => {
console.log(key, value);
});
}
iterateObject();
Output
book Sherlock Holmes author Arthur Conan Doyle genre Mystery
Syntax:
Object.entries(object).forEach(([key, value]) => {
console.log(key, value);
});
Approach 3: Using Object.keys() and forEach()
The Object.keys() method returns an array containing the object's own enumerable keys. We can use forEach() to iterate over these keys and access their corresponding values.
Example: Iterates over an object's keys and accesses their values.
function iterateObject() {
let exampleObj = {
book: "Sherlock Holmes",
author: "Arthur Conan Doyle",
genre: "Mystery"
};
Object.keys(exampleObj).forEach(key => {
const value = exampleObj[key];
console.log(`${key}: ${value}`);
});
}
iterateObject();
Output
book: Sherlock Holmes author: Arthur Conan Doyle genre: Mystery
Syntax:
Object.keys(object).forEach(key => {
console.log(key, object[key]);
});
Note: Object.entries() is generally the most convenient approach when you need both the key and value during iteration.