How to combine 2 maps into a third map in JavaScript

3 Answers

0 votes
// Objects
const map1 = { a: "aaa", b: "bbb" };
const map2 = { c: "ccc", b: "XYZ", d: "ddd" }; // 'b' will be overwritten


const combined = { ...map1, ...map2 };

console.log(combined);



/*
run:

{ a: 'aaa', b: 'XYZ', c: 'ccc', d: 'ddd' }

*/

 



answered Aug 26, 2025 by avibootz
0 votes
const map1 = new Map([
  ["a", "aaa"],
  ["b", "bbb"]
]);

const map2 = new Map([
  ["c", "ccc"],
  ["b", "XYZ"], // Overwrites 'b'
  ["d", "ddd"]
]);

const combined = 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 = new Map([
  ["a", "aaa"],
  ["b", "bbb"]
]);

const map2 = new Map([
  ["c", "ccc"],
  ["b", "XYZ"], // Overwrites 'b'
  ["d", "ddd"]
]);

const combined = 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

2 answers 104 views
2 answers 83 views
3 answers 92 views
2 answers 100 views
1 answer 71 views
1 answer 81 views
...