How to combine 2 maps into a third map in TypeScript

2 Answers

0 votes
const map1: Map<string, string> = new Map([
  ["a", "aaa"],
  ["b", "bbb"]
]);
 
const map2: Map<string, string> = new Map([
  ["c", "ccc"],
  ["b", "XYZ"], // Overwrites 'b'
  ["d", "ddd"]
]);
 
const combined: Map<string, string> = new Map([...map1, ...map2]);
 
console.log(combined);
 
 
 
/*
run:

Map (4) {"a" => "aaa", "b" => "XYZ", "c" => "ccc", "d" => "ddd"} 
 
*/

 



answered Aug 26, 2025 by avibootz
0 votes
const map1: Map<string, string> = new Map([
  ["a", "aaa"],
  ["b", "bbb"]
]);
 
const map2: Map<string, string> = new Map([
  ["c", "ccc"],
  ["b", "XYZ"], // Overwrites 'b'
  ["d", "ddd"]
]);
 
const combined: Map<string, string> = new Map(map1);
 
for (const [key, value] of map2) {
  if (combined.has(key)) {
    combined.set(key, combined.get(key) + ", " + value); // Merge values
  } else {
    combined.set(key, value);
  }
}
 
console.log(combined);
 
 
 
/*
run:

Map (4) {"a" => "aaa", "b" => "bbb, XYZ", "c" => "ccc", "d" => "ddd"} 
 
*/

 



answered Aug 26, 2025 by avibootz

Related questions

...