I have my old results in result1 and updated values in result2 . If both ids from the 2 arrays are same then i want to change the new value from result2 in result1
var result1 = [
{id:1, name:'Sandra', email:'[email protected]'},
{id:2, name:'John', email:'[email protected]'},
{id:3, name:'Peter', email:'[email protected]'},
{id:4, name:'Bobby', email:'[email protected]'}
];
var result2 = [
{id:2, name:'Andreas', email:'[email protected]'},
{id:4, name:'Season', email:'[email protected]'}
];
I want to update the result1 with result2 values like below if Ids are same
var result1 = [
{id:1, name:'Sandra', email:'[email protected]'},
{id:2, name:'Andreas', email:'[email protected]'},
{id:3, name:'Peter', email:'[email protected]'},
{id:4, name:'Season', email:'[email protected]'}
];
Please help
Best Answer
You could put
result1
elements in Map using theid
as key and the records as value.Then if you need to update only the existing records, without adding the new values to the map, you can loop over
result2
and add its records to the map only if theirid
is already in the map.If
result2
can hold only records whose id is inresult1
or ifresult2
may have more records thatresult1
and you want to keep the new ones too, you can remove theif
inresult2
loop.