How to iterate over a JavaScript object ?
Iteration involves looping through the object's properties one by one. Depending on the method used, you can access and manipulate different levels of properties efficiently. Here are several methods.
There are many methods to iterate over an object which are discussed below:
Table of Content
Method 1: Using for...in Loop
The properties of the object can be iterated over using a for..in loop. This loop is used to iterate over all non-symbol iterable properties of an object. Some objects may contain properties that may be inherited from their prototypes. The hasOwnProperty() method can be used to check if the property belongs to the object itself. The value of each key of the object can be found by using the key as the index of the object.
Syntax:
for (let key in exampleObj) {
if (exampleObj.hasOwnProperty(key)) {
value = exampleObj[key];
console.log(key, value);
}
}
Example: This example shows the implementation of the above-explained approach.
function iterateObject() {
let exampleObj = {
book: "Sherlock Holmes",
author: "Arthur Conan Doyle",
genre: "Mystery"
};
for (let key in exampleObj) {
if (exampleObj.hasOwnProperty(key)) {
value = exampleObj[key];
console.log(key, value);
}
}
}
iterateObject();
Output
book Sherlock Holmes author Arthur Conan Doyle genre Mystery
Method 2: Using Object.entries() and map() Method
The Object.entries() method is used to return an array of the object's own enumerable string-keyed property pairs. The returned array is used with the map() method to extract the key and value from the pairs. The key and values from the key-value pair can be extracted by accessing the first and second index of the array pair. The first index corresponds to the key and the second index corresponds to the value of the pair.
Syntax:
Object.entries(exampleObj).map(entry => {
let key = entry[0];
let value = entry[1];
console.log(key, value);
});
Example: This example shows the implementation of above-explained approach.
function iterateObject() {
let exampleObj = {
book: "Sherlock Holmes",
author: "Arthur Conan Doyle",
genre: "Mystery"
};
Object.entries(exampleObj).map(entry => {
let key = entry[0];
let value = entry[1];
console.log(key, value);
});
}
iterateObject();
Output
book Sherlock Holmes author Arthur Conan Doyle genre Mystery
Method 3: Using forEach() and object.keys() Method
object.keys() Method returns an array of keys of the object and forEach() method is an array method that allows you to iterate over each element in the array.
Example: This example shows the implementation of above-explained approach.
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