简体   繁体   English

在对象数组中添加匹配键的值

[英]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. 我想遍历数组,如果键匹配,我想将每个键的结果相加并返回每个键之和的一个对象。

ie

{a: 6, b: 9, c: 6, d: 3}

The code I currently have is 我目前拥有的代码是

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;
    }, {});
}

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 我想我很难理解reduce方法的工作原理-https://developer.mozilla.org/zh-CN/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. 另外,我觉得这是应该在SO上某个位置而不需要使用库的答案。

Thanks in advance. 提前致谢。

Using Array.reduce() and Array.map() 使用Array.reduce()和Array.map()

var tab = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}];

function sum(tab) {
  return tab.reduce((a, b) => {
    Object.keys(b).map(c => a[c] = (a[c] || 0) + b[c]);
    return a;
  });
}

console.log(sum(tab));

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];
}

try this 尝试这个

 resobj = {}; [{a: 2,b: 5,c: 6}, {a: 3,b: 4,d: 1}, {a: 1,d: 2}].forEach(function(v) { var keys = Object.keys(v); for (i = 0; i < keys.length; i++) { if (typeof resobj[keys[i]] == 'undefined') { resobj[keys[i]] = Number(v[keys[i]]); } else { resobj[keys[i]] += v[keys[i]]; } } }) document.write(JSON.stringify(resobj)) 

Your callback function in reduce() needs two arguments: 您在reduce()回调函数需要两个参数:

  1. The result returned for the previous value (or the initial value if the first one) 返回上一个值的结果(如果是第一个,则返回初始值)
  2. The current value in the loop 循环中的当前值

You should also pass an empty object as a second parameter to reduce. 您还应该传递一个空对象作为第二个参数来减少。 This is the one you will fill in. 这是您要填写的。

 var input = [ {a: 2, b: 5, c: 6}, {a: 3, b: 4, d: 1}, {a: 1, d: 2} ]; var answer = input.reduce(function(prev, curr) { for (var p in curr) { prev[p] = (prev[p] || 0) + curr[p]; } return prev; // this will be passed as prev in the next iteration or returned as the result. }, {}); // The {} is the initial value passed as prev console.log(answer); 

Yet another solution with reduce: 另一个带有reduce的解决方案:

 var result = [{a: 2, b: 5, c: 6}, {a:3, b: 4, d:1},{a: 1, d: 2}].reduce(function(prev, current) { Object.keys(current).forEach(function(key) { prev[key] = (prev[key] || 0) + current[key]; }); return prev; }, {}); document.write('<pre>' + JSON.stringify(result, 0, 2) + '</pre>'); 

Just use Array#forEach() and an object for the result. 只需使用Array#forEach()和一个对象作为结果。

 var data = [{ a: 2, b: 5, c: 6 }, { a: 3, b: 4, d: 1 }, { a: 1, d: 2 }], obj = {}; data.forEach(function (o) { Object.keys(o).forEach(function (k) { obj[k] = (obj[k] || 0) + o[k]; }); }) document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>'); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM