使用lodash按键和求和值合并嵌套数组

时间:2017-06-06 09:33:09

标签: lodash

var arr1 = [{
    "name": { "s1": 2 },
    "type": { "t1": 2 },
    "info": { "m1": 2 },
    "date": "2017-06-04"
  },
  {
    "name": { "s1": 3 },
    "type": { "t1": 3 },
    "info": { "m1": 3 },
    "date": "2017-06-05"
  }
];

var arr2 = [{
  "name": { "s1": 1 },
  "type": { "t1": 0 },
  "info": { "m1": 2 },
  "date": "2017-06-05"
}];

我有两个数组需要的结果如下:

[
  {
    "name": { "s1": 2 },
    "type": { "t1": 2 },
    "info": { "m1": 2 },
    "date": "2017-06-04"
  },
  {
    "name": { "s1": 4 },
    "type": { "t1": 3 },
    "info": { "m1": 5 },
    "date": "2017-06-05"
  }
]

1 个答案:

答案 0 :(得分:2)

使用lodash,连接数组,groupBy date,并合并对象。合并时,如果两个值都是数字,则返回它们的总和。

var arr1 = [{"name":{"s1":2},"type":{"t1":2},"info":{"m1":2},"date":"2017-06-04"}, {"name":{"s1":3},"type":{"t1":3},"info":{"m1":3},"date":"2017-06-05"}];

var arr2 = [{"name":{"s1":1},"type":{"t1":0},"info":{"m1":2},"date":"2017-06-05"}];

var result = _(arr1)
  .concat(arr2)
  .groupBy('date')
  .map(function(group) {
    return _.mergeWith({}, ...group, function(o1, o2) {
      if(_.isNumber(o1) && _.isNumber(o1)) {
        return o1 + o2;
      }
    });
  })
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>