Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Danka & Peter
To convert a Map
to an array of objects:
Array.from()
method, passing it the Map
as the first parameter
and a function as the second.Array.from
method creates a new array from an iterable object, such as
a Map
.const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); const arr = Array.from(map, ([key, value]) => { return {[key]: value}; }); // 👇️ [{name: 'Bob'}, {country: 'Chile'}] console.log(arr);
We passed the following parameters to the Array.from method:
map
function that gets called with each element in the arrayIf we call the Array.from
method without the map
function, we get a two
dimensional array.
const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); // 👇️ [['name', 'Bob'], ['country', 'Chile']] const arr = Array.from(map); console.log(arr);
The function we passed to the Array.from
method gets invoked with each element
in the array.
In our arrow function, we use the square bracket []
syntax to destructure the
elements of the array.
const [a, b] = ['hello', 'world']; console.log(a); // 👉️ hello console.log(b); // 👉️ world
An easy way to think about this is - we are grabbing the value of the first
array element and assigning it to the variable named a
.
Whatever we return from this function gets added to the return value from
Array.from
.
map (Array.map)
function. It allows us to iterate over an array and create a new array, based on the returned values.We use the dynamic property key syntax []
to set the key of the object to the
actual key of the Map
.
const arr = Array.from(map, ([key, value]) => { // 👇️ return {[key]: value}; });
A simple way to think about the dynamic key assignment is - we are basically
evaluating the variable key
and setting the object's key to the result.
const a = 'name'; const obj = { [a]: 'Bob', }; console.log(obj); // 👉️ {name: 'Bob'}
Once the function iterates over all of the array elements, we have the complete array of objects.
Here's an example that achieves the same goal, however is a bit more readable if
you're not familiar with how Array.from
works.
const map = new Map(); map.set('name', 'Bob'); map.set('country', 'Chile'); // 👇️ [['name', 'Bob'], ['country', 'Chile']] const arr = Array.from(map); console.log(arr); // 👇️ [{name: 'Bob', country: 'Chile'}] const arrOfObj = arr.map(([key, value]) => { return {[key]: value}; }); console.log(arrOfObj);
Instead of passing the
Array.map
function as a parameter to the Array.from
method, we use it separately.
Everything works in the exact same way as the previous code snippet.