How to merge the Maps in JavaScript
In this tutorial, we are going to learn about how to merge the Maps in JavaScript with the help of examples.
Merging means the joining of two or more maps into a single map.
Consider, we have the following two maps:
const a = new Map([["car", "audi"]]);
const b = new Map([["speed", 100]]);
Now, we need to join above two maps like this:
{'car' => 'audi', 'speed' => 100}
Using spread operator (…)
To merge the two or more maps into a single map, we can use the spread(…) operator in JavaScript.
The spread operator unpacks the iterables (such as maps, arrays, objects, etc) into a individual elements.
Here is an example:
const a = new Map([["car", "audi"]]);
const b = new Map([["speed", 100]]);
const result = new Map([[...a, ...b]]);
console.log(result);
Output:
{'car' => 'audi', 'speed' => 100}
We can also concatenate three maps in JavaScript like this:
const a = new Map([["car", "audi"]]);
const b = new Map([["speed", 100]]);
const c = new Map([["cc", 2500]]);
const result = new map([[...a, ...b, ...c]]);
console.log(result);
Output:
{'car' => 'audi', 'speed' => 100, 'cc' => 2500}