对数组中对象的所有属性求和 [英] Sum all properties of objects in array

查看:926
本文介绍了对数组中对象的所有属性求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据集:

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

我需要对所有数组元素求和以得到以下结果:

I need to sum all the array elements to get following result:

const output = { f: 7, x: 3, y: 5, z: 4 };

我不知道参数名称,所以我们不应该在任何地方痛它.

I don't know the parameters names so we should not sore it anywhere.

将输入数组中的所有对象合并为一个的[strong>最短方法是什么?

What is the shortest way to merge (sum properties) all the objects from the input array into one ?

可以使用ES6功能和lodash.

There is possibility to use ES6 features and lodash.

推荐答案

我想这是最短的解决方案:

I guess this is the shortest possible solution:

const input = [
  { x: 1, y: 3 },
  { y: 2, f: 7 },
  { x: 2, z: 4 }
];

let result = _.mergeWith({}, ...input, _.add);

console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>

文档:

  • https://lodash.com/docs/4.17.2#mergeWith,
  • https://lodash.com/docs/4.17.2#add

如果您可以替换input的第一个元素,则可以省略第一个参数:

If you're fine with the first element of input being replaced, you can omit the first argument:

 _.mergeWith(...input, _.add)

这篇关于对数组中对象的所有属性求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆