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 will do what you need:
var origArr = [
{name: 'Trump', isRunning: true},
{name: 'Cruz', isRunning: true},
{name: 'Kasich', isRunning: true}
];
var updatingArr = [
{name: 'Cruz', isRunning: false},
{name: 'Kasich', isRunning: false}
];
for (var i = 0; i < updatingArr.length; ++i) {
var updateItem = updatingArr[i];
for (var j = 0; j < origArr.length; ++j) {
var origItem = origArr[j];
if (origItem.name == updateItem.name) {
origItem.isRunning = updateItem.isRunning;
break;
}
}
}
document.write('<pre>' + JSON.stringify(origArr, 0, 4) + '</pre>');
Same as @gevorg answer, but you may want to also add a new object to the original array if no matches are found.
let combinedEvents = origEvents;
for(let i =0; i< newEvents.length; i++){
let newEvent = newEvents[i];
for(let j =0; j< origEvents.length; j++){
let origEvent = origEvents[j];
if(newEvent.events_id == origEvent.events_id){
combinedEvents.splice(j,1, newEvent);
break;
} else if(j === origEvents.length - 1){
combinedEvents.push(newEvent);
break;
}
}
}
Using a double for loop and splice you can do it like so:
for(var i = 0, l = origArr.length; i < l; i++) {
for(var j = 0, ll = updatingArr.length; j < ll; j++) {
if(origArr[i].name === updatingArr[j].name) {
origArr.splice(i, 1, updatingArr[j]);
break;
}
}
}
Example here
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)
Here's a solution using underscore:
var result = _.map(origArr, function(orig){
return _.extend(orig, _.findWhere(updatingArr, {name: orig.name}));
});