如何使用lodash通过键合并两个不同大小的对象数组

时间:2017-04-24 05:59:17

标签: javascript merge lodash

我有一组像

这样的对象
var data = {"part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}],
            "part2":[{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}]
           };

我需要合并part1和part2(最好是用lodash)来获取

var result = [
              {"id": 1, "a": 50, "b": 40},
              {"id": 2, "a": 55},
              {"id": 3, "b": 45},
              {"id": 4, "a": 100, "b": 110}
             ];

注意:我需要根据id进行合并,如果存在,则按原样复制其他对象。第1部分和第2部分的大小和顺序会有所不同,并且它们也可能没有任何共同的ID。

3 个答案:

答案 0 :(得分:3)

您可以使用lodash的_.groupBy()_.merge()将具有相同属性的多个对象(在本例中为id)合并为一个:



var data = {"part1": [{"id": 1, "a": 50},{"id": 2, "a": 55},{"id": 4, "a": 100}], "part2":[{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}] };

var result = _(data)
  .values() // extract the arrays from the object
  .flatten() // flatten them to a single array
  .groupBy('id') // group them by the ids
  .map(function(values) { // map the groups
    return _.merge.apply(_, [{}].concat(values)); // merge all elements in the group. I'm using apply to merge the array of object, and add an empty object, so the original objects won't be mutated
  })
  .value(); // finish the chain

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个

var data = {"part1": [{"id": 1, "a": 50}, {"id": 2, "a": 55}, {"id": 4, "a": 100}],
    "part2": [{"id": 1, "b": 40}, {"id": 3, "b": 45}, {"id": 4, "b": 110}]
};

var finalArr = [];

// Collecting all items with common ids
for (var i = 0; i < data.part1.length; i++) {
    var tempi = data.part1[i];
    for (var j = 0; j < data.part2.length; j++) {
        var tempj = data.part2[j];
        if (tempi.id == tempj.id) {
            tempi.b = tempj.b;
            finalArr.push(tempi);
        }
    }
}

// collecting the remaining items
for (var k = 0; k < data.part2.length; k++) {
    var tempk = data.part2[k];
    var itemFound = false;
    for (var l = 0; l < finalArr.length; l++) {
        var templ = finalArr[l];
        if (tempk.id == templ.id) {
            itemFound = true;
        }
    }
    if (!itemFound) {
        finalArr.push(tempk);
    }
}

console.log(finalArr.toString());

//finalArr is the result you want

答案 2 :(得分:0)

您可以对给定对象的所有键使用动态方法,并将所有属性合并到具有相同id的对象。稍后对数组进行排序。

var data = { part1: [{ id: 1, a: 50 }, { id: 2, a: 55 }, { id: 4, a: 100 }], part2: [{ id: 1, b: 40 }, { id: 3, b: 45 }, { id: 4, b: 110 }] },
    result = Object.keys(data).reduce(function (hash) {
        return function (r, k) {
            data[k].forEach(function (o) {
                if (!hash[o.id]) {
                    hash[o.id] = {};
                    r.push(hash[o.id]);
                }
                Object.keys(o).forEach(function (l) {
                    hash[o.id][l] = o[l];
                });
            });
            return r;
        };
    }(Object.create(null)), []);

result.sort(function (a, b) { return a.id - b.id; });
  
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }