简体   繁体   中英

Merging of two arrays with conditions without using lodash

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM