我有这样的数据:
var data = [
{2: 1, 6: 1},
{2: 2},
{1: 3, 6: 2},
];
(“2”类似于键,“1”表示“计数”)
我希望像这样输出:
output = [
{2: 3, 6: 3, 1: 3},
];
有没有办法使用lodash存档?
答案 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;