Sean O Sean O - 7 months ago 97
Javascript Question

JavaScript - merge two arrays of objects and de-duplicate based on property value

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 = [
{name: 'Trump', isRunning: true},
{name: 'Cruz', isRunning: true},
{name: 'Kasich', isRunning: true}
var updatingArr = [
{name: 'Cruz', isRunning: false},
{name: 'Kasich', isRunning: false}
// desired result:
NEWArr = [
{name: 'Trump', isRunning: true},
{name: 'Cruz', isRunning: false},
{name: 'Kasich', isRunning: false}

I've tried concat() & Underscore's
function, but it always dumps the newer object & returns, essentially, the original array.

Is there a way to overwrite (replace)
with the objects in
-- matching on the


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]);

Example here