I want to update (replace) the objects in my array with the objects in another array. Each object has the same structure. e.g.
var origArr = [
This version lets you define the selector
that defines an object as duplicate.
>= 0
if two selectors are equal. If none are equal, it returns -1
const origArr = [
{name: 'Trump', isRunning: true},
{name: 'Cruz', isRunning: true},
{name: 'Kasich', isRunning: true}
];
const updatingArr = [
{name: 'Cruz', isRunning: false},
{name: 'Kasich', isRunning: false}
];
const mergeArrayOfObjects = (original, newdata, selector = 'key') => {
newdata.forEach(dat => {
const foundIndex = original.findIndex(ori => ori[selector] == dat[selector]);
if (foundIndex >= 0) original.splice(foundIndex, 1, dat);
else original.push(dat);
});
return original;
};
const result = mergeArrayOfObjects(origArr, updatingArr, "name")
console.log('RESULT -->', result)