-3
var arr1 = [{
    id: '111',
    name: 'aaa'
}, {
    id: '222',
    name: 'bbb'
}, {
    id: '333',
    name: 'ccc'
}, {
    id: '444',
    name: 'ddd'
}];


var arr2 = [{
    id: '111',
    name: 'xyz'
}, {
    id: '333',
    name: 'abc'
}];

my requirement: I need to replace aar1 with arr2 having same id in arr2 but different name value.

Below Result i should get in arr1

var arr1 = [{
    id: '111',
    name: 'xyz'
}, {
    id: '222',
    name: 'bbb'
}, {
    id: '333',
    name: 'abc'
}, {
    id: '444',
    name: 'ddd'
}];
Zenoo
  • 12,670
  • 4
  • 45
  • 69
Soumya Behera
  • 2,325
  • 4
  • 15
  • 25
  • 2
    Possible duplicate of [Replacing objects in array](https://stackoverflow.com/questions/37585309/replacing-objects-in-array) – str Jul 23 '18 at 14:01
  • @str dont mark this quest as possible dup. I have asked this question for my requirement. The question earlier asked was for different requirement. – Soumya Behera Jul 24 '18 at 05:09
  • How is it different? Even the answers that you got are exactly the same as in the duplicate. – str Jul 24 '18 at 06:25

2 Answers2

2

you can use map and find to replace arr2 name in arr1. map function iterate through each elements of arr1, find will match both id and return matched object if found. if we don't find we will just return arr1 item using || operator.

const result = arr1.map(item =>  arr2.find(item2 => item.id === item2.id) || item)

Working example:

var arr1 = [{
  id: '111',
  name: 'aaa'
}, {
  id: '222',
  name: 'bbb'
}, {
  id: '333',
  name: 'ccc'
}, {
  id: '444',
  name: 'ddd'
}];


var arr2 = [{
  id: '111',
  name: 'xyz'
}, {
  id: '333',
  name: 'abc'
}];

const result = arr1.map(item =>  arr2.find(item2 => item.id === item2.id) || item)
console.log(result)
Amit Chauhan
  • 6,151
  • 2
  • 24
  • 37
0

This is my interpretation of the question. Only copy the name if the id is found in arr2.

arr1.forEach(e1 => {
    var e2 = arr2.find( e => e.id === e1.id );
    if (e2) { e1.name = e2.name; }
});
rioV8
  • 24,506
  • 3
  • 32
  • 49