I am trying to merge 2 Maps. In ES6 I would do it like so and it works perfectly fine:
const m1 = new Map();
m1.set('foo', 1);
const m2 = new Map();
m2.set('bar', 3);
const m3 = new Map([...m1, ...m2]);
If i do the same in TS i get the following an error:
Type 'Map<string, number>' is not an array type.
I assume that i have to cast it to array somehow but I did not find a working solution. How should i go about fixing this issue?
Explicitly type the keys and values of the third Map. Use the spread syntax (...) to unpack the key-value pairs of the first two Maps. The types of the keys and values of the Maps have to match.
concat() Alternatively, we can use Stream#concat() function to merge the maps together. This function can combine two different streams into one. As shown in the snippet, we are passed the streams of map1 and map2 to the concate() function and then collected the stream of their combined entry elements.
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.
This works also with target ES5:
let map1:Map<string, number> = new Map([["a", 1], ["b", 2]]);
let map2:Map<string, number> = new Map([["c", 1], ["d", 2]]);
let mergedMap:Map<string, number> = new Map([...Array.from(map1.entries()), ...Array.from(map2.entries())]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With