Borislav Hadzhiev
Last updated: Oct 19, 2021
Check out my new book
To convert the keys of a Map
to an array:
keys()
method on the Map
to get an iterator object that contains
all of the keys in the Map
.Array.from()
method, passing it the iterator as a parameter. The
Array.from
method creates a new array from an iterable object.const map = new Map(); map.set('name', 'John'); map.set('age', 30); const keys = Array.from(map.keys()); console.log(keys); // 👉️ ['name', 'age'] console.log(keys.length); // 👉️ 2
We used the
Map.keys
method to get an iterator object containing the keys of the Map
.
We passed the iterator as the only parameter to the Array.from method.
The Array.from
method converts the iterable into an array and returns the new
array instance.
An alternative approach is to use the spread operator (...).
To convert the keys of a Map
object to an array:
keys()
method on the Map
to get an iterator object that contains
the keys of the Map
.const map = new Map(); map.set('name', 'John'); map.set('age', 30); const keys = [...map.keys()]; console.log(keys); // 👉️ ['name', 'age'] console.log(keys.length); // 👉️ 2
We used the spread operator to include all of the Map
's keys into a new array.
Map
into an array.You could also do this with multiple Map
s.
const map1 = new Map(); map1.set('name', 'John'); map1.set('age', 30); const map2 = new Map(); map2.set('country', 'Chile'); const keys = [...map1.keys(), ...map2.keys()]; console.log(keys); // 👉️ ['name', 'age', 'country'] console.log(keys.length); // 👉️ 3