Published on

TypeScript: How to merge two Maps

Table of Contents

Shallow copy: Overwriting keys in the first map with values from the second map.

ts-map-merge-shallow.ts
interface Member {
  fullName: string
  subscriptionID?: number
}

const map1 = new Map<string, Member>([
  ['John', { fullName: 'John Doe' }],
  ['Jane', { fullName: 'Jane Smith' }],
])

const map2 = new Map<string, Member>([
  ['Mary', { fullName: 'Mary Johnson' }],
  ['Jane', { fullName: 'Jane Doe', subscriptionID: 123 }],
])

const mergedMap = new Map([...map1, ...map2])

console.log(mergedMap.get('John')); // { fullName: 'John Doe' }
console.log(mergedMap.get('Jane')); // { fullName: 'Jane Doe', subscriptionID: 123 }
console.log(mergedMap.get('Mary')); // { fullName: 'Mary Johnson' }

Here, we create two maps map1 and map2, and then merge map2 into map1 by spreading both maps into a new map. The result is a new map that contains the keys and values from both map1 and map2. Since map2 overwrites the value of the key 'key2' in map1, the resulting map has 'key2' => 'newValue2'.

Note: that this is a shallow copy, meaning that if the values in the maps are objects, the merged map will have references to the same objects as the original maps.

Deep copy: Merging keys and values from both maps into a new map.

ts-map-merge-deep.ts
interface Member {
fullName: string
subscriptionID?: number
}

const map1 = new Map<string, Member>([
['John', { fullName: 'John Doe' }],
['Jane', { fullName: 'Jane Smith' }],
]);

const map2 = new Map<string, Member>([
['Mary', { fullName: 'Mary Johnson' }],
['Jane', { fullName: 'Jane Doe', subscriptionID: 123 }],
]);

// Merge map2 into map1
const mergedMap = new Map([
...Array.from(map1.entries()),
...Array.from(map2.entries()),
].map(([key, value]) => [key, Object.assign({}, value)]));

console.log(mergedMap.get('John')); // { fullName: 'John Doe' }
console.log(mergedMap.get('Jane')); // { fullName: 'Jane Doe', subscriptionID: 123 }
console.log(mergedMap.get('Mary')); // { fullName: 'Mary Johnson' }

//we cannot mutate the merged map if we performe changes into original maskPosition
map1.delete('John')
map2.set('Mary', { fullName: 'Maria Johnson' })
console.log(mergedMap.get('John')); // { fullName: 'John Doe' }
console.log(mergedMap.get('Mary'));// { fullName: 'Mary Johnson' }

Here, we create two maps map1 and map2, and then merge them into a new map mergedMap.

To perform a deep copy, we use Object.assign() to create a new object for each value in the map.

We first create an array of entries from both maps using Array.from(), and then map over each entry

to create a new array of entries with the same key and a new object for the value.

The resulting map has a new object for each value, so changes to one map will not affect the other map.

Note: that this is a more complex solution than the first example, but it performs a deep copy of the values in the maps.