JavaScript merging objects by id

前端 未结 16 1634
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 09:43

What\'s the correct way to merge two arrays in Javascript?

I\'ve got two arrays (for example):

var a1 = [{ id : 1, name : \"test\"}, { id : 2, name :         


        
16条回答
  •  醉酒成梦
    2020-11-22 10:45

    ES6 simplifies this:

    let merge = (obj1, obj2) => ({...obj1, ...obj2});
    

    Note that repeated keys will be merged, and the value of the second object will prevail and the repeated value of the first object will be ignored.

    Example:

    let obj1 = {id: 1, uniqueObj1Key: "uniqueKeyValueObj1", repeatedKey: "obj1Val"};
    let obj2 = {id: 1, uniqueObj2Key: "uniqueKeyValueObj2", repeatedKey: "obj2Val"};
    
    merge(obj1, obj2)
    // {id: 1, uniqueObj1Key: "uniqueKeyValueObj1", repeatedKey: "obj2Val", uniqueObj2Key: "uniqueKeyValueObj2"}
    merge(obj2, obj1)
    // {id: 1, uniqueObj2Key: "uniqueKeyValueObj2", repeatedKey: "obj1Val", uniqueObj1Key: "uniqueKeyValueObj1"}
    

    Complete solution (with Lodash, not Underscore)

    var a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}]
    var a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}]
    var merge = (obj1, obj2) => ({...obj1, ...obj2});
    _.zipWith(a1, a2, merge)
    (2) [{…}, {…}]
       0: {id: 1, name: "test", count: "1"}
       1: {id: 2, name: "test2", count: "2"}
    

    If you have an array of arrays to merge you can do it like this:

    var arrayOfArraysToMerge = [a1, a2, a3, a4]; //a3 and a4 are arrays like a1 and a2 but with different properties and same IDs.
    _.zipWith(...arrayOfArraysToMerge, merge)
    (2) [{…}, {…}]
       0: {id: 1, name: "test", count: "1", extra1: "val1", extra2: 1}
       1: {id: 2, name: "test2", count: "2", extra1: "val2", extra2: 2}
    

提交回复
热议问题