LWC – How to Compare Array of Objects

arrayjslightning-web-components

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 the id 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 their id is already in the map.

const resultMap = new Map();
// Fill the map with result1 elements
result1.forEach((elem) => {
    resultMap.set(elem.id, elem);
});

// Update the map values
result2.forEach((elem) => {
    if (resultMap.has(elem.id)) {
        resultMap.set(elem.id, elem);
    }
});

result1 = Array.from(resultMap.values());

If result2 can hold only records whose id is in result1 or if result2 may have more records that result1 and you want to keep the new ones too, you can remove the if in result2 loop.

result2.forEach((elem) => {
    resultMap.set(elem.id, elem);
});