How to merge Maps using JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20211 min read

Merge Map Objects using JavaScript #

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.

index.js
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.

index.js
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:

index.js
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.

index.js
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);
Note that the insertion order of keys is preserved. If you need to re-order the key-value pairs, simply switch the order in which the spread operator (...) is used.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee