I have two arrays of objects result1 and result2
var result1 = [
{id:1, name:'Sandra'},
{id:2, name:'John'},
{id:3, name:'Peter'},
{id:4, name:'Bobby'}
];
var result2 = [
{id:2, name:'Malai'},
{id:4, name:'Lama'}
];
I want to update the name if id matches. My goal is:
var result1 = [
{id:1, name:'Sandra'},
{id:2, name:'Malai'},
{id:3, name:'Peter'},
{id:4, name:'Lama'}
];
var result1 = [{
id: 1,
name: 'Sandra'
},
{
id: 2,
name: 'John'
},
{
id: 3,
name: 'Peter'
},
{
id: 4,
name: 'Bobby'
}
];
var result2 = [{
id: 2,
name: 'Malai'
},
{
id: 4,
name: 'Lama'
}
];
let results = result1.map(x => {
let el = result2.find(y => y.id === x.id);
if (el) return {
...x,
name: el.name
};
return x;
});
console.log(results)
var result1 = [
{id:1, name:'Sandra'},
{id:2, name:'John'},
{id:3, name:'Peter'},
{id:4, name:'Bobby'}
];
var result2 = [
{id:2, name:'Malai'},
{id:4, name:'Lama'}
];
const finalResult = result1.map((user, index) => {
const match = result2.find(({ id }) => user.id === id)
return match ? { ...user, name: match.name } : user
})
console.log(finalResult)
You can achieve that using map to map the result1 and the use find to match the current item inside the map to see if the result2 contains an object matching that id, if that's the case return the a new object containing the current user but with the match name, if not just return the user
Try the snipped below. The code is pretty simple. We iterate through each object (person) of the first result array. For each of those persons we will iterate result2. If the same id is found, that person's object will be overwritten. The output of the code is a third array with the goal you presented.
var result1 = [
{id:1, name:'Sandra'},
{id:2, name:'John'},
{id:3, name:'Peter'},
{id:4, name:'Bobby'}
];
var result2 = [
{id:2, name:'Malai'},
{id:4, name:'Lama'}
];
const finalResult = result1.map(person => {
for (let i = 0; i < result2.length; i++) {
if(person.id === result2[i].id){
person = result2[i];
break;
}
}
return person;
});
console.log(finalResult);