Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing objects in array

I have this javascript object:

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

I need to replace objects in arr1 with items from arr2 with same id.

So here is the result I want to get:

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

How can I implement it using javascript?

like image 581
Michael Avatar asked Jun 02 '16 07:06

Michael


People also ask

How do I change an object's value in an array of objects?

To change the value of an object in an array:Call the findIndex() method to get the index of the specific object. Access the array at the index and change the property's value using dot notation. The value of the object in the array will get updated in place.

How do you replace an object in an array react?

To replace an object in an array in React state: Use the map() method to iterate over the array. On each iteration, check if a certain condition is met. Replace the object that satisfies the condition and return all other objects as is.

How do you replace an object in an array of keys?

To change the key name in an array of objects with JavaScript, we use the array map method. const arrayOfObj = [ { key1: "value1", key2: "value2", }, { key1: "value1", key2: "value2", }, ]; const newArrayOfObj = arrayOfObj. map(({ key1: stroke, ... rest }) => ({ stroke, ...


2 Answers

You can use Array#map with Array#find.

arr1.map(obj => arr2.find(o => o.id === obj.id) || obj); 

var arr1 = [{      id: '124',      name: 'qqq'  }, {      id: '589',      name: 'www'  }, {      id: '45',      name: 'eee'  }, {      id: '567',      name: 'rrr'  }];    var arr2 = [{      id: '124',      name: 'ttt'  }, {      id: '45',      name: 'yyy'  }];    var res = arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);    console.log(res);

Here, arr2.find(o => o.id === obj.id) will return the element i.e. object from arr2 if the id is found in the arr2. If not, then the same element in arr1 i.e. obj is returned.

like image 85
Tushar Avatar answered Sep 24 '22 02:09

Tushar


What's wrong with Object.assign(target, source) ?

enter image description here

Arrays are still type object in Javascript, so using assign should still reassign any matching keys parsed by the operator as long as matching keys are found, right?

like image 23
Jonathan Avatar answered Sep 25 '22 02:09

Jonathan