Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 merge two array of objects and override the existing object

I have 2 array of objects:

const arr1 = [{'id':'1' 'value':'yes'}, {'id':'2', 'value':'no'}];
const arr2 = [{'id':'2', 'value':'yes'}];

So, if I try and merge these 2 arrays the result should be:

arrTemp = [{'id':'1', 'value':'yes'}, {'id':'2', 'value':'yes'}];

Basically, it should work similar to Object.assign(), but no matter what I try it does not work. Could anyone please help me in this ?

I modified the data structure. Is it possible to merge them now and get the output.

Thanks

like image 599
Ashy Ashcsi Avatar asked Nov 29 '17 14:11

Ashy Ashcsi


People also ask

How do you combine two arrays into an array of objects?

To combine two arrays into an array of objects, use map() from JavaScript.

How do I merge an array of objects into one?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.


1 Answers

This is how you can get the job done with ES6 spread, reduce and Object.values.

const arr1 = [{
  'id': '1',
  'value': 'yes'
}, {
  'id': '2',
  'value': 'no'
}];
const arr2 = [{
  'id': '2',
  'value': 'yes'
}];

const result = Object.values([...arr1, ...arr2].reduce((result, {
  id,
  ...rest
}) => {
  result[id] = {
    ...(result[id] || {}),
    id,
    ...rest
  };
  return result;
}, {}));

console.log(result);
like image 98
Madura Pradeep Avatar answered Sep 30 '22 23:09

Madura Pradeep