Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Autri Taheri
To convert the values of a Map
to an array:
Call the values()
method on the Map
to get an iterator object that
contains all of the values in the Map
.
Call the 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 values = Array.from(map.values()); console.log(values); // 👉️ ['John', 30] console.log(values.length); // 👉️ 2 const keys = Array.from(map.keys()); // 👉️ ['name', 'age']
We used the
Map.values
method to get an iterator object containing the values 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 values of a Map
object to an array:
values()
method on the Map
to get an iterator object that
contains the values of the Map
.const map = new Map(); map.set('name', 'Tom'); map.set('age', 39); const values = [...map.values()]; console.log(values); // 👉️ ['Tom', 39] console.log(values.length); // 👉️ 2 const keys = [...map.keys()]; // 👉️ ['name', 'age']
We used the spread operator (...) to include all of the values of the Map
into
a new array.
Map
into an array.You can also do this with multiple Map
s.
const map1 = new Map(); map1.set('name', 'Tom'); const map2 = new Map(); map2.set('country', 'Chile'); const values = [...map1.values(), ...map2.values()]; console.log(values); // 👉️ ['Tom', 'Chile'] console.log(values.length); // 👉️ 2