The Object entries() method
By Flavio Copes
Learn how the JavaScript Object.entries() method returns an array of an object own [key, value] pairs, how it works with arrays, and how to count properties.
Object.entries() returns an array containing all the object own properties, as an array of [key, value] pairs. It was introduced in ES2017.
Usage:
const person = { name: 'Fred', age: 87 }
Object.entries(person) // [['name', 'Fred'], ['age', 87]]
Object.entries() also works with arrays. The keys are the indexes, as strings:
const people = ['Fred', 'Tony']
Object.entries(people) // [['0', 'Fred'], ['1', 'Tony']]
Why is this useful?
Objects are not iterable. You can’t loop over one with for...of directly. Object.entries() gives you an array, and arrays are iterable.
Combined with destructuring, this is the cleanest way to loop over an object:
const person = { name: 'Fred', age: 87 }
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`)
}
// name: Fred
// age: 87
You can also use it to count the number of properties an object contains, combined with the length property of the array:
Object.entries(person).length //2
Transforming an object
Object.fromEntries(), added in ES2019, does the reverse: it builds an object from an array of pairs. Together they let you map over an object’s properties:
const prices = { bread: 3, milk: 2 }
const doubled = Object.fromEntries(
Object.entries(prices).map(([item, price]) => [item, price * 2])
)
// { bread: 6, milk: 4 }
The same pairs format is what Map expects, so converting an object to a Map is one line:
const map = new Map(Object.entries(person))
map.get('name') //'Fred'
The companion methods
Object.entries() has two siblings. Object.keys() returns just the keys, and Object.values() returns just the values:
Object.keys(person) // ['name', 'age']
Object.values(person) // ['Fred', 87]
Reach for these when you only need one side of the pair. Use entries() when you need both.
What it does not return
Object.entries() only returns the object’s own enumerable properties with string keys. Properties inherited from the prototype are skipped, and so are properties keyed by a Symbol.
One thing to be careful with: calling it on null or undefined throws.
Object.entries(null)
// TypeError: Cannot convert undefined or null to object
This bites you when the object comes from an API response or an optional parameter. If the value can be missing, guard it with a fallback:
Object.entries(data ?? {})
That gives you an empty array instead of a crash.
Related posts about js: