This article is an interactive version of this article by Dr. Axel Rauschmayer.

All the code snippets of this page are live and interactive powered by the klipse plugin:

  1. Live: The code is executed in your browser
  2. Interactive: You can modify the code and it is evaluated as you type

The code is transpiled with Babel Standalone.

The following ECMAScript proposal is at stage 4: “Object.values/Object.entries” by Jordan Harband. This blog post explains it.

Object.entries() and Object.values()

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

Properties, whose keys are symbols, are ignored:

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

Arrays are coerced into Objects:

Object.entries(["a", "b"])

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(k,  v);
}

Setting up Maps via Object.entries()

Object.entries() also lets you set up a Map (read more about 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,
    }));
    map

FAQ: Object.entries()

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

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

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