在对象数组中添加匹配键的值 [英] Add values of matching keys in array of objects
问题描述
我有一个包含许多具有匹配键的对象的数组:
I have an array with a number of objects with matching keys:
[{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}]
我想循环遍历数组,如果键匹配,我想添加每个键的结果,并返回一个具有每个键之和的对象。
I want to loop through the array and if the keys match I want to add the results of each and return one object with the sum of each key.
即
{a: 6, b: 9, c: 6, d: 3}
我目前的代码是
function combine() {
var answer = [];
for(var i in arguments){
answer.push(arguments[i])
}
answer.reduce(function(o) {
for (var p in o)
answer[p] = (p in answer ? answer[p] : 0) + o[p];
return answer;
}, {});
}
我可以找到答案 here 如果我要使用下划线库,但是我希望这样做它没有使用库。我想我很难理解 reduce
方法是如何工作的 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
I can find the answer here if I was to use the underscore library, however I wish to do it without using a library. I think I am having difficulty understanding how the reduce
method works - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
如何解决这个问题的任何帮助将不胜感激。此外,我觉得这是一个答案应该是在某个地方,而不必使用库。
Any help as to how to solve this would be greatly appreciated. Also, I feel it is an answer that should be somewhere on SO without having to use a library.
提前致谢。
推荐答案
遍历每个对象并添加它。
Loop through each object and add it.
var a = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}];
var ans = {};
for(var i = 0; i < a.length; ++i){
for(var obj in a[i]){
ans[obj] = ans[obj] ? ans[obj] + a[i][obj] : a[i][obj];
}
}
document.write(JSON.stringify(ans));
ans[obj] = ans[obj] ? ans[obj] + a[i][obj] : a[i][obj];
This line is the same as
// check if the object already exists(or not falsy) in answer, if Yes add that value to the new value
if(ans[obj])
{
ans[obj] = ans[obj] + a[i][obj];
}
// else create a new object in the answer and set it to the value from the array
else
{
ans[obj] = a[i][obj];
}
这篇关于在对象数组中添加匹配键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!