How to convert Map keys to array?

Lilleman picture Lilleman · Feb 11, 2016 · Viewed 283k times · Source

Lets say I have the following map:

let myMap = new Map().set('a', 1).set('b', 2);

And I want to obtain ['a', 'b'] based on the above. My current solution seems so long and horrible.

let myMap = new Map().set('a', 1).set('b', 2);
let keys = [];
for (let key of myMap)
  keys.push(key);
console.log(keys);

There must be a better way, no?

Answer

pawel picture pawel · Feb 11, 2016

Map.keys() returns a MapIterator object which can be converted to Array using Array.from:

let keys = Array.from( myMap.keys() );
// ["a", "b"]

EDIT: you can also convert iterable object to array using spread syntax

let keys =[ ...myMap.keys() ];
// ["a", "b"]