How to convert Map keys to array?

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?


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"]

You can use the spread operator to convert Map.keys() iterator in an Array.

let myMap = new Map().set('a', 1).set('b', 2).set(983, true)
let keys = [...myMap.keys()]
console.log(keys)