Michael Michael - 2 years ago 65
Javascript Question

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:'em'},
{id:'45',name:'yyy'},
{id:'567',name:'eme'}]


How can I implement it using javascript?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download