Javascript Map merge

Introduction

Maps can be merged, maintaining key uniqueness:

Merge two maps. The last repeated key wins.

Spread operator essentially converts a Map to an Array

let first = new Map([
  [1, 'one'],/*from w ww .  j  av a 2s. c o m*/
  [2, 'two'],
  [3, 'three'],
]);

let second = new Map([
  [1, 'uno'],
  [2, 'dos']
]);

let merged = new Map([...first, ...second])

console.log(merged.get(1)); // uno
console.log(merged.get(2)); // dos
console.log(merged.get(3)); // three

Maps can be merged with Arrays:

The last repeated key wins.

let first = new Map([
  [1, 'one'],/*from  w  w w .  ja v  a2 s .  c  o m*/
  [2, 'two'],
  [3, 'three'],
]);

let second = new Map([
  [1, 'uno'],
  [2, 'dos']
]);


let merged = new Map([...first, ...second, [1, 'eins']]);

console.log(merged.get(1)); // eins
console.log(merged.get(2)); // dos
console.log(merged.get(3)); // three



PreviousNext

Related