合并JS对象数组

时间:2017-07-25 11:35:30

标签: javascript object merge

好的,我有两个想要合并的对象,但想知道最好的方法是什么......

obj1 = [
         { 
           id: 123, 
           list: [ {id:1}, {id:2}, {id: 3} ]
         },
         {
           id: 456
           list: [ {id:99}, {id:98}, {id: 97} ]
         }
       ]


obj1 = [
         { 
           id: 123, 
           list: [ {id:1}, {id:4}, {id: 5} ]
         },
         {
           id: 456
           list: [ {id:99}, {id:100}, {id: 101} ]
         }
       ]

我希望能够调用类似merge(obj1, obj2)的内容,结果如下:

resultObj = [
         { 
           id: 123, 
           list: [ {id:1}, {id:2}, {id:3}, {id:4}, {id: 5} ]
         },
         {
           id: 456
           list: [ {id:99}, {id:98}, {id:97}, {id:100}, {id: 101} ]
         }
       ]

2 个答案:

答案 0 :(得分:0)

您可以使用forEach()在第一级按ID分组元素,然后再使用forEach()find()来检查列表中的对象并推送到数组或分配给现有对象相同的身份。

var obj1 = [{"id":123,"list":[{"id":1},{"id":2},{"id":3}]},{"id":456,"list":[{"id":99},{"id":98},{"id":97}]}]
var obj2 = [{"id":123,"list":[{"id":1},{"id":4},{"id":5}]},{"id":456,"list":[{"id":99},{"id":100},{"id":101}]}]  
       
var result = []       
var arr = [].concat(obj1, obj2)
arr.forEach(function(e) {
  if(!this[e.id]) result.push(this[e.id] = e)
  else {
    var that = this;
    e.list.forEach(function(a) {
      var o = that[e.id].list.find(c => a.id == c.id);
      o ? Object.assign(o, a) : that[e.id].list.push(a)
    })
  }
}, {})    
     
console.log(result)

答案 1 :(得分:0)

您可以将嵌套哈希表用于相同的id属性。此解决方案复制对象中的所有属性。

function merge(source, target, hash) {
    source.forEach(function (o) {
        if (!hash[o.id]) {
            hash[o.id] = { _: Object.create(null), data: { id: o.id } };
            target.push(hash[o.id].data);
        }
        Object.keys(o).forEach(function (k) {
            if (['id', 'list'].indexOf(k) !== -1) {
                return;
            }
            hash[o.id].data[k] = o[k];
        });
        if (o.list) {
            hash[o.id].data.list = hash[o.id].data.list || [];
            merge(o.list, hash[o.id].data.list, hash[o.id]._);
        }
    });
}

var array1 = [{ id: 123, list: [{ id: 1, a: 3 }, { id: 2 }, { id: 3 }] }, { id: 456, list: [{ id: 99 }, { id: 98 }, { id: 97 }] }],
    array2 = [{ id: 123, list: [{ id: 1, b: 4 }, { id: 4 }, { id: 5 }] }, { id: 456, list: [{ id: 99 }, { id: 100 }, { id: 101 }] }],
    hash = Object.create(null),
    result = [];

[array1, array2].forEach(function (a) {
    merge(a, result, hash);
});
   
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }