[Solved] javascript delete elements from array of objects that are not present in another array of objects


You can use map to walk arr2 and use find to get the matching element.

Try it online!

const arr1 = [{Id: 1, Name:'test'}, {Id: 2, Name:'test2'}]
const arr2 = [{value:'test'}, {value:'test3'}]

const newArray = arr2.map(x => {
    // we search for the matching element.
    const item = arr1.find(obj => obj.Name === x.value)
    // if item exists get item, else create a new one
    return item ? item : { Id: null, Name: x.value }
});
console.log(JSON.stringify(newArray))

output

[{"Id":1,"Name":"test"},{"Id":null,"Name":"test3"}]

1

solved javascript delete elements from array of objects that are not present in another array of objects