Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two Maps in TypeScript

Tags:

typescript

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?

like image 350
Nick Avatar asked Oct 31 '17 12:10

Nick


People also ask

How do I merge two Maps in TypeScript?

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.

How can I merge two Maps?

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.

How do I use two Maps in 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.


1 Answers

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())]);
like image 172
Reducer Avatar answered Sep 20 '22 22:09

Reducer