Iterating over Object properties in JavaScript
There are several ways to iterate over an object’s properties in JavaScript.
Object.entries() returns an array of object’s own enumerable string-keyed property [key, value]
pairs. This array can then be iterated over using forEach() or for…of.
Example
const book = {
"title": "The Fountainhead",
"author": "Ayn Rand",
"pages": 753
};
Object.entries(book).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
Output
title: The Fountainhead
author: Ayn Rand
pages: 753
Similarly, for...of
can also be used with Object.entries()
.
for (let [key, value] of Object.entries(book)) {
console.log(`${key}: ${value}`);
}
for…in
for...in
statement can also be used to iterate over object properties, but it also iterates over inherited properties. Luckily, hasOwnProperty() method can be used to check if a property is object’s own property.
const book = {
"title": "The Fountainhead",
"author": "Ayn Rand",
"pages": 753
};
for (let key in book) {
if (book.hasOwnProperty(key)) {
console.log(`${key}: ${book[key]}`);
}
}
Object.keys() and Object.values()
If we are only concerned with object property keys, then Object.keys()
can be used. Similarly, Object.values()
can be used to get object property values.
const book = {
"title": "The Fountainhead",
"author": "Ayn Rand",
"pages": 753
};
Object.keys(book).forEach(key => {
console.log(key);
});
Object.values(book).forEach(value => {
console.log(value);
});