Manipulating objects in array of objects in JavaScript



Suppose, we have two arrays of objects like this −

const arr1 = [
   {id:'124',name:'qqq'},
   {id:'589',name:'www'},
   {id:'45',name:'eee'},
   {id:'567',name:'rrr'}
];
const arr2 = [
   {id:'124',name:'ttt'},
   {id:'45',name:'yyy'}
];

We are required to write a JavaScript function that takes in two such objects. Our function should search the first array for objects with the same "id" property that is present in the second array.

Then our function should replace the "name" property of those objects with the corresponding "name" property of the second array's objects.

Therefore, for the above arrays, the output should look like −

const output = [
   {id:'124',name:'ttt'},
   {id:'589',name:'www'},
   {id:'45',name:'yyy'},
   {id:'567',name:'rrr'}
];

Example

The code for this will be −

const arr1 = [
   {id:'124',name:'qqq'},
   {id:'589',name:'www'},
   {id:'45',name:'eee'},
   {id:'567',name:'rrr'}
];
const arr2 = [
   {id:'124',name:'ttt'},
   {id:'45',name:'yyy'}
];
const replaceByOther = (arr1, arr2) => {
   for(let i = 0; i < arr1.length; i++){
      const el = arr1[i];
      const index = arr2.findIndex(elm => el['id'] === elm['id']);
      if(index === -1){
         continue;
      };
      else['name'] = arr2[index]['name'];
   };
};
replaceByOther(arr1, arr2);
console.log(arr1);

Output

And the output in the console will be −

[
   { id: '124', name: 'ttt' },
   { id: '589', name: 'www' },
   { id: '45', name: 'yyy' },
   { id: '567', name: 'rrr' }
]

Advertisements