Please support this book: buy it (PDF, EPUB, MOBI) or donate

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()

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

7.1.2 Object.values()

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

7.2 Object.entries()

This method has the following signature:

  1. 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:

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

Properties, whose keys are symbols, are ignored:

  1. > Object.entries({ [Symbol()]: 123, foo: 'abc' });
  2. [ [ '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):

  1. let obj = { one: 1, two: 2 };
  2. for (let [k,v] of Object.entries(obj)) {
  3. console.log(`${JSON.stringify(k)}: ${JSON.stringify(v)}`);
  4. }
  5. // Output:
  6. // "one": 1
  7. // "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.

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

7.2.2 FAQ: Object.entries()

  • Why is the return value of Object.entries() an Array and not an iterator?The relevant precedent in this case is Object.keys(), not, e.g., Map.prototype.entries().
  • Why does Object.entries() only return the enumerable own string-keyed properties?Again, this is done to be consistent with Object.keys(). That method also ignores properties whose keys are symbols. Eventually, there may be a method Reflect.ownEntries() that returns all own properties.

7.3 Object.values()

Object.values() has the following signature:

  1. 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:

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