如何使用lodash使用相同的密钥对数据求和?

时间:2018-03-05 08:53:18

标签: lodash

我有这样的数据:

var data = [
{2: 1, 6: 1},
{2: 2},
{1: 3, 6: 2},

];

(“2”类似于键,“1”表示“计数”)

我希望像这样输出:

output = [
{2: 3, 6: 3, 1: 3}, 

];

有没有办法使用lodash存档?

1 个答案:

答案 0 :(得分:1)

使用带有展开的_.mergeWith()合并所有密钥并对其值求和:



const data = [{2: 1, 6: 1}, {2: 2}, {1: 3, 6: 2}];

const result = _.mergeWith({}, ...data, (objValue, srcValue) =>
  _.isNumber(objValue) ? objValue + srcValue : srcValue);

console.log(result);

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