I have an array of object and an object
for eg: arr=[{id:1,name:"foo"},{id:2,name:"bar"}]
and my new object is obj={id:1,name:"baz"}
.I want to replace the obj based on key inside an array.
The expected out is
output=[{id:1,name:"baz"},{id:2,name:"bar"}]
I have done some work around like following:
function removeObjBasedID(arr, obj) {
let newArr = [];
arr.map((item, i) => {
if (item.id == obj.id) {
newArr.splice(i, 1);
} else {
newArr = [...arr, obj];
}
});
return newArr;
}
console.log(removeObjBasedID(arr, obj));