I have two arrays that look like this
let array1 = [{
'id': 1,
'name': 'A'
}, {
'id': 2,
'name': 'B'
}, {
'id': 3,
'name': 'C'
}]
let array2 = [{
'id': 1,
'name': 'x'
}, {
'id': 2,
'name': 'y'
}]
My goal is to update the values in array 1 with the corresponding object values from array 2, based on matching id values. The expected result should be:
[{
'id': 1,
'name': 'x'
}, {
'id': 2,
'name': 'y'
}, {
'id': 3,
'name': 'C'
}]
I tried the following code but it's not functioning correctly.
array1.forEach(item1 => {
const itemFromArr2 = array2.find(item2 => item2.id == item1.id);
if (itemFromArr2) {
item1 = itemFromArr2;
}
})
If you have any suggestions on how to achieve this, please advise. Thank you.