In this article we will learn how to convert a map to an array.
It is very common to convert a map to an array in JavaScript.
Problem
We have a problem, which is that we want to convert a map to an array
Imagine we have a map like this:
// Map
const map = new Map([
['name', 'John'],
['age', 30]
]);
console.log(map);
// Map(2) { 'name' => 'John', 'age' => 30 }
And we want to convert this map to an array.
How to solve this problem
We can solve this problem by more than one way:
- Using
Array.from()
method - Using spread operator
...
Convert a map to an array using Array.from
We can use Array.from
method to convert a map to an array.
Example
// Map
const map = new Map([
['name', 'John'],
['age', 30]
]);
// Convert map to an array
const toArray = Array.from(map);
// Result:
console.log(toArray);
Output
[ [ 'name', 'John' ], [ 'age', 30 ] ]
Convert a map to an array using spread operator
We can use spread operator ...
to convert the map to an array as well.
// Map
const map = new Map([
['name', 'John'],
['age', 30]
]);
// Convert map to an array
const toArray = [...map];
// Result:
console.log(toArray);
Output
[ [ 'name', 'John' ], [ 'age', 30 ] ]
Thank you for reading
Thank you for reading my blog. 🚀