I want to Add/Replace the object from array of objects by testing some properties against array object
Replace
object if name and id matchesAdd
objectto thearray if name and id does not match from array objects
I am using below code, its working fine but I am not sure is it a good solution.
let arr = [{name: 'test1', id:1, data: {a:1} }, {name:'test2', id:2, data: {a:2}}]
let obj = {name:'test3', id:3, data: {a:3}}
let itemFound = false;
let newArr = arr.map((item)=>{
let test = item.name === obj.name && item.id === obj.id;
if(test){
itemFound = true;
}
return test ? obj : item;
});
if(!itemFound){
newArr.push(obj);
}
console.log(newArr)
wrapit in afunction?