1

I want to work with two arrays by comparing them and do some merging of properties:

I have my array1 and array2 as :

array1 = [
          { id: 10, name: 'abc', otherData: 'other' },
          { id: 20, name: 'def', otherData: 'other' },
          { id: 30, name: 'ghi', otherData: 'other' },
        ];
array2 = [
          { id: 10, nameV2: 'xyz', otherData: 'other' },
          { id: 20, nameV2: 'pqr', otherData: 'other' },
          { id: 30, nameV2: 'tvs', otherData: 'other' },
        ];

I'm expecting this result where I will compare both arrays, iterate over elements, if id is same then have nameV2 key from array2 in array1's elements

expected output :

array1 = [
          { id: 10, name: 'abc', otherData: 'other', nameV2: 'xyz' },
          { id: 20, name: 'def', otherData: 'other', nameV2: 'pqr' },
          { id: 30, name: 'ghi', otherData: 'other', nameV2: 'tvs' },
        ];

how to achieve this?

Aniruddha
  • 39
  • 1
  • 5
  • This question's answers answer this question: [How to find differences between two JavaScript arrays of objects?](https://stackoverflow.com/questions/39074429/how-to-find-differences-between-two-javascript-arrays-of-objects) – Heretic Monkey Aug 09 '22 at 20:47

2 Answers2

2

Here's an approach to do this, we create a look-up map(idNameV2Map) using array2 and then use it to get the desired output

const array1 = [{ id: 10, name: 'abc', otherData: 'other' }, { id: 20, name: 'def', otherData: 'other' }, { id: 30, name: 'ghi', otherData: 'other' }];
const array2 = [{ id: 10, nameV2: 'xyz', otherData: 'other' }, { id: 20, nameV2: 'pqr', otherData: 'other' },{ id: 30, nameV2: 'tvs', otherData: 'other' }];

const idNameV2Map = array2.reduce((acc, curr) => {
   acc[curr.id] = curr.nameV2;
   return acc;
}, {});

const output = array1.map((item) => {
   if (idNameV2Map[item.id]) {
       return { ...item, nameV2: idNameV2Map[item.id] };
   }

   return item;
});

console.log(output);
Abito Prakash
  • 4,368
  • 2
  • 13
  • 26
1

Another approach using Array.find()
with conditionally add nameV2 property to the object if it's exist.

const array1 = [{ id: 10, name: 'abc', otherData: 'other' }, { id: 20, name: 'def', otherData: 'other' }, { id: 30, name: 'ghi', otherData: 'other' }];
const array2 = [{ id: 10, nameV2: 'xyz', otherData: 'other' }, { id: 20, nameV2: 'pqr', otherData: 'other' },{ id: 30, nameV2: 'tvs', otherData: 'other' }];

const output = array1.map((item) => {
    let objFound = array2.find(obj=>obj.id===item.id);
   return { ...item, ...(objFound && {nameV2: objFound.nameV2}) };
});

console.log(output);
XMehdi01
  • 5,538
  • 2
  • 10
  • 34