[英]Sum all properties of objects in array
我有以下数据集:
const input = [
{ x: 1, y: 3 },
{ y: 2, f: 7 },
{ x: 2, z: 4 }
];
我需要对所有数组元素求和以得到以下结果:
const output = { f: 7, x: 3, y: 5, z: 4 };
我不知道参数名称,所以我们不应该在任何地方痛。
将输入数组中的所有对象合并为一个的最短方法是什么?
有可能使用ES6功能和lodash。
我想这是最短的解决方案:
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>
文件:
如果您可以替换input
的第一个元素,则可以省略第一个参数:
_.mergeWith(...input, _.add)
将Array#forEach
方法与Object.keys
方法一起使用。
const input = [{ x: 1, y: 3 }, { y: 2, f: 7 }, { x: 2, z: 4 }]; // object for result var res = {}; // iterate over the input array input.forEach(function(obj) { // get key from object and iterate Object.keys(obj).forEach(function(k) { // define or increment object property value res[k] = (res[k] || 0) + obj[k]; }) }) console.log(res);
具有ES6箭头功能
const input = [{ x: 1, y: 3 }, { y: 2, f: 7 }, { x: 2, z: 4 }]; var res = {}; input.forEach(obj => Object.keys(obj).forEach(k => res[k] = (res[k] || 0) + obj[k])) console.log(res);
您可以迭代密钥和总和。
var input = [{ x: 1, y: 3 }, { y: 2, f: 7 }, { x: 2, z: 4 }], sum = input.reduce((r, a) => (Object.keys(a).forEach(k => r[k] = (r[k] || 0) + a[k]), r), {}); console.log(sum);
使用_.mergeWith
_.reduce(input, function(result, item) {
return _.mergeWith(result, item, function(resVal, itemVal) {
return itemVal + (resVal || 0);
});
}, {});
const input = [ { x: 1, y: 3 }, { y: 2, f: 7 }, { x: 2, z: 4 } ]; function sumProperties(input) { return input.reduce((acc, obj) => { Object.keys(obj).forEach((key) => { if (!acc[key]) { acc[key] = 0 } acc[key] += obj[key] }) return acc }, {}) } console.log( sumProperties(input) )
将forEach
与Object.keys
结合forEach
const input = [
{ x: 1, y: 3 },
{ y: 2, f: 7 },
{ x: 2, z: 4 }
];
const output = { f: 7, x: 3, y: 5, z: 4 };
output = {}
input.forEach(function(obj){
Object.keys(obj).forEach(function(key){
output.key = output.key ? output.key + key || key
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.