1

I am facing problem to merge the two arrays. I have two arrays of objects first is prev having old values and another with updated values. I would like to have result array with all the objects of prev array with its updated value in array next, and also have objects in next array.

Example:

var prev = [{id: 1, val: 'abc'}, {id: 2, val: 'pqr'}];
var next = [{id: 1, val: 'nextVal'}, {id: 3, val: 'xyz'}];

expected

mergeOutput = [
  {id: 1, val: 'nextVal'}, // value is updated 
  {id: 2, val: 'pqr'}, 
  {id: 3, val: 'xyz'}
]

Note: Array order do not matter.

Harish
  • 1,841
  • 1
  • 13
  • 26

1 Answers1

6

You can use Map() to merge array.

var prev = [{id: 1, val: 'abc'}, {id: 2, val: 'pqr'}];
var next = [{id: 1, val: 'nextVal'}, {id: 3, val: 'xyz'}];

var hash = new Map();
prev.concat(next).forEach(function(obj) {
    hash.set(obj.id, Object.assign(hash.get(obj.id) || {}, obj))
});

var mergedArray = Array.from(hash.values());
console.log(mergedArray);

Source : StackOverflow

Hassan Imam
  • 21,956
  • 5
  • 41
  • 51