Use JavaScript's Object.entries() for iterating over an object's properties
In this article, we'll see how to use JavaScript's Object.entries()
method for iterating over an object's properties with the help of forEach()
and for...of
loops.
Object.entries()
is a new ES8 method for navigating an object's keys and values.
The Object.entries()
method returns an array of arrays. Two elements make up each array within the array. The property key is the first element, and the value is the second.
Here is an example:
const food = {
grapes: '🍇',
melon: '🍈',
watermelon: '🍉'
}
If you define the previous array in the browser's console and then console log the food
array you'll get the following output:
console.log(food);
{grapes: "🍇", melon: "🍈", watermelon: "🍉"}
If you call food.entries()
with your previous array you'll get:
const entries = Object.entries(food)
console.log(entries)
(3) [Array(2), Array(2), Array(2)]
0: (2) ["grapes", "🍇"]
1: (2) ["melon", "🍈"]
2: (2) ["watermelon", "🍉"]
length: 3
The output is an array of arrays. Each array has two elements, the key and value of each food property.
You can iterate over the array returned by the Object.entries()
method using the for...of
loop or the forEach()
method. Let's see how!
Let's start with forEach()
:
js
Object.entries(food).forEach(([key, value]) => {
console.log(`${key}: ${value}`)
});
Here we used the array destruction to get the key and value of each property but we can also access the elements by their index.
You can also use the for...of
loop as follows:
for (const el of Object.entries(food)) {
console.log(`${el[0]}: ${el[1]}`)
};
Here we used the index to access the property's elements.
We can also use array destruction as follows:
for (const [key, value] of Object.entries(food)) {
console.log(`${key}: ${value}`)
};
In this article, we learned about the JavaScript's Object.entries()
method for iterating over an object's properties with the help of forEach()
and for...of
loops.
-
Date: