Borislav Hadzhiev
Thu Oct 28 2021·1 min read
Photo by Nirzar Pangarkar
To merge Maps, use the spread operator (...) to unpack the values of two or
more Maps into an array and pass them into the Map()
constructor, e.g.
new Map([...map1, ...map2])
. The new Map
will contain the key-value pairs
from all provided Map
objects.
const map1 = new Map([['name', 'Tom']]); const map2 = new Map([['age', 30]]); const map3 = new Map([...map1, ...map2]); // 👇️ {'name' => 'Tom', 'age' => 30} console.log(map3);
We used the
spread operator (...)
to unpack the key-value pairs from 2 Map
objects into an array.
const map1 = new Map([['name', 'Tom']]); // 👇️ [ ['name', 'Tom'] ] console.log([...map1]);
The array contains nested arrays consisting of key-value pairs.
The last step is to pass the array to the Map() constructor, which takes an iterable as a parameter.
With the values in place, the example looks like:
const map3 = new Map([['name', 'Tom'], ['age', 30]])
The iterable, the Map
takes must consist of key-value pairs, e.g. a two
dimensional array or another Map
object.
This process could be repeated with as many Map
objects as necessary.
const map1 = new Map([['name', 'Tom']]); const map2 = new Map([['age', 30]]); const map3 = new Map([['country', 'Chile']]); const map4 = new Map([...map1, ...map2, ...map3]); // 👇️ {'name' => 'Tom', 'age' => 30, 'country' => 'Chile'} console.log(map4);