Table of contents
Please support this book: buy it (PDF, EPUB, MOBI) or donate
(Ad, please don’t block.)

7. Object.entries() and Object.values()

This chapter describes the ECMAScript 2017 feature “Object.values/Object.entries” by Jordan Harband.

7.1 Overview

7.1.1 Object.entries()

let obj = { one: 1, two: 2 };
for (let [k,v] of Object.entries(obj)) {
    console.log(`${JSON.stringify(k)}: ${JSON.stringify(v)}`);
}
// Output:
// "one": 1
// "two": 2

7.1.2 Object.values()

> Object.values({ one: 1, two: 2 })
[ 1, 2 ]

7.2 Object.entries()

This method has the following signature:

Object.entries(value : any) : Array<[string,any]>

If a JavaScript data structure has keys and values then an entry is a key-value pair, encoded as a 2-element Array. Object.entries(x) coerces x to an Object and returns the entries of its enumerable own string-keyed properties, in an Array:

> Object.entries({ one: 1, two: 2 })
[ [ 'one', 1 ], [ 'two', 2 ] ]

Properties, whose keys are symbols, are ignored:

> Object.entries({ [Symbol()]: 123, foo: 'abc' });
[ [ 'foo', 'abc' ] ]

Object.entries() finally gives us a way to iterate over the properties of an object (read here why objects aren’t iterable by default):

let obj = { one: 1, two: 2 };
for (let [k,v] of Object.entries(obj)) {
    console.log(`${JSON.stringify(k)}: ${JSON.stringify(v)}`);
}
// Output:
// "one": 1
// "two": 2

7.2.1 Setting up Maps via Object.entries()

Object.entries() also lets you set up a Map via an object. This is more concise than using an Array of 2-element Arrays, but keys can only be strings.

let map = new Map(Object.entries({
    one: 1,
    two: 2,
}));
console.log(JSON.stringify([...map]));
    // [["one",1],["two",2]]

7.2.2 FAQ: Object.entries()

7.3 Object.values()

Object.values() has the following signature:

Object.values(value : any) : Array<any>

It works much like Object.entries(), but, as its name suggests, it only returns the values of the own enumerable string-keyed properties:

> Object.values({ one: 1, two: 2 })
[ 1, 2 ]
Next: 8. New string methods: padStart and padEnd