Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

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 193 views
2 answers 146 views
3 answers 179 views
2 answers 176 views
1 answer 128 views
2 answers 158 views
1 answer 129 views
...