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": "To Kill a Mockingbird",
"author": "Harper Lee",
"pages": 281
};
Object.entries(book).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});Output
title: To Kill a Mockingbird
author: Harper Lee
pages: 281Similarly, 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": "To Kill a Mockingbird",
"author": "Harper Lee",
"pages": 281
};
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": "To Kill a Mockingbird",
"author": "Harper Lee",
"pages": 281
};
Object.keys(book).forEach(key => {
console.log(key);
});
Object.values(book).forEach(value => {
console.log(value);
});