Understanding Object.entries()
A quick guide to understanding `Object.entries()`
👉 The Object.entries()
method is used to return a 2D array consisting of enumerable property [key, value]
pairs of the object. It creates a pair of all of your object's properties and their respective values.
let's take a look at the syntax.
Object.entries(object);
👉 Here are some of the major points you have to remember while using Object.entries()
It loops in the same order as a
for...in
loop does.One important difference is that a
for...in
loop enumerates properties in the prototype chain as well.The order of the array returned by
Object.entries()
does not depend on how an object is defined. You can always sort the array based on your own criteria using.sort()
on the returned array.Object.entries
is such a useful method when you need both a key and value at the same time. You can let go of the traditional approach offor...in
orfor
loop.
Examples:
👉 Basic Usage
// Basic example:
const user = {
name: 'Mike',
age: 30,
}
Object.entries(user) // Output: [ ['name', 'Mike'], ['age', 30] ]
👉 Looping approaches
const user = {
firstName: 'John',
lastName: 'Wick',
age: 30,
isActive: false,
}
// Traditional approach using `for...in` loop
for (let key in user) {
console.log(`${key}: ${user[key]}`)
}
// Using `Object.entries()`
Object.entries(user).forEach((item) => {
console.log(`${item.key}: ${item.value}`
}))
// 👉 Output in both cases:
/*
firstName: John
lastName: Wick
age: 30
isActive: false
*/
You can also use the power of destructuring in javascript to make it easier to understand.
// With array destructuring
Object.entries(user).forEach(([key, value]) => console.log(`${key}: ${value}`))
That's it, folks! hope it was a good read for you. Thank you! ✨
👉 References:
The official documentation of Object.entries()