【问题标题】:how to merge two object arrays of different size by key using lodash如何使用lodash按键合并两个不同大小的对象数组
【发布时间】:2017-09-20 16:51:09
【问题描述】:

我有一个对象数组,比如

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 进行合并,如果存在,则照原样复制其他对象。 part1 和 part2 的大小和顺序会有所不同,它们也可能没有任何共同的 id。

【问题讨论】:

标签: javascript merge lodash


【解决方案1】:

您可以使用 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>

【讨论】:

    【解决方案2】:

    您可以对给定对象的所有键使用动态方法,并将所有属性合并到具有相同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; }

    【讨论】:

      【解决方案3】:

      试试这个

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-01
        • 2017-06-08
        • 1970-01-01
        • 2020-09-16
        • 2018-05-27
        • 1970-01-01
        相关资源
        最近更新 更多