2016-12-03 61 views
0

我有以下数据集:总和数组对象的所有属性

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。

+2

低质量的问题。失望-_- – naomik

+0

@naomik不要判断 - 每个人都有糟糕的一天。 – hsz

回答

4

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

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) 
3

使用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 arrow function

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);

3

你可以遍历键和总和。

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);

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) 
 
)

1

使用_.mergeWith

_.reduce(input, function(result, item) { 
    return _.mergeWith(result, item, function(resVal, itemVal) { 
     return itemVal + (resVal || 0); 
    }); 
}, {}); 
+0

是的,'mergeWith' - 但做得对(看上面) – georg

+0

@georg是的,你是对的,美丽的解决方案 – stasovlas

0

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 
    }) 
})