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?
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.
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.
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, ...
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.
What's wrong with Object.assign(target, source)
?
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With