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

后端 未结 11 1635
渐次进展
渐次进展 2021-02-03 14:36

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 = [
          


        
11条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-03 14:58

    You could use Array#map in combination with Array#reduce

    var origArr = [{ name: 'Trump', isRunning: true }, { name: 'Cruz', isRunning: true }, { name: 'Kasich', isRunning: true }],
        updatingArr = [{ name: 'Cruz', isRunning: false }, { name: 'Kasich', isRunning: false }],
        NEWArr = origArr.map(function (a) {
            return this[a.name] || a;
        }, updatingArr.reduce(function (r, a) {
            r[a.name] = a;
            return r;
        }, Object.create(null)));
    
    document.write('
    ' + JSON.stringify(NEWArr, 0, 4) + '
    ');

提交回复
热议问题