简体   繁体   English

根据匹配键添加对象值

[英]Adding object values based on matching keys

I have an array of objects and I'm trying to combine like keys and add the values. 我有一个对象数组,我试图像键一样组合并添加值。 So X should be 0, Y should be 1, and B should be 3. Thanks for any help!!!! 因此X应该为0,Y应该为1,B应该为3。谢谢您的帮助!

const arr = [{X: -1}, {Y: 1}, {X: -4}, {B: 3}, {X: 5}];

let result = {};
for (let i = 0; i < arr.length; i++) {
    var item = arr[i];
    for (var key in item) {
        if (!(key in result))
            parseInt(item);
            result[key] = [];
            result[key] += item[key];
    }
}

console.log(result);

I expected X to be 0 but instead it is returning 5. 我期望X为0,但返回5。

You could use Array.prototype.reduce with Object.entries to group by key in order to summate the values. 您可以将Array.prototype.reduceObject.entries一起使用以按键分组,以求和。

Example below (check the comments for more details): 下面的示例(查看注释以获取更多详细信息):

 const arr = [{ X: -1 }, { Y: 1 }, { X: -4 }, { B: 3 }, { X: 5 }]; //Iterate the object els in the arr const map = arr.reduce((accum, el) => { //Destructure the object into some clearly defined variables const [ [key, value] ] = Object.entries(el); //Check the key against the map if (accum[key] != null) { //Add the value to the existing map value accum[key] += value; } else { //Set the initial value in the map accum[key] = value; } return accum; }, {}); console.log(map); 

You can reduce each item (object) by grabbing the key and assigning the added previous value with the current value. 您可以通过抓住键并为添加的先前值分配当前值来减少每个项目(对象)。

 const input = [ {X: -1}, {Y: 1}, {X: -4}, {B: 3}, {X: 5} ]; let response = input.reduce((obj, item) => { return ((key) => Object.assign(obj, { [key] : (obj[key] || 0) + item[key] // Add previous with current }))(Object.keys(item)[0]); }); console.log(response); 
 .as-console-wrapper { top: 0; max-height: 100% !important; } 

Result 结果

{
  "X": 0,
  "Y": 1,
  "B": 3
}

Fun Code Golf Experiment 趣味高尔夫实验

I changed Object.assign(o,{[k]:(o[k]||0)+e[k]}) to ({...o,[k]:(o[k]||0)+e[k]}) by utilizing the spread operator to save 10 bytes. 我将Object.assign(o,{[k]:(o[k]||0)+e[k]})更改为({...o,[k]:(o[k]||0)+e[k]}) ,利用扩展运算符可以节省10个字节。

 r=i=>i.reduce((o,e) =>(k=>({...o,[k]:(o[k]||0)+e[k]}))(Object.keys(e)[0])) // 74 bytes console.log(r([{X:-1},{Y:1},{X:-4},{B:3},{X:5}])) 
 .as-console-wrapper { top: 0; max-height: 100% !important; } 

Here is inner loop changed such that we access the key, if exists, it's used; 这是内部循环的更改,以便我们访问密钥(如果存在),它将被使用; otherwise it's initialized to zero. 否则将其初始化为零。 Then value is added. 然后添加值。

const arr = [{X: -1}, {Y: 1}, {X: -4}, {B: 3}, {X: 5}];

let result = {};
for (let i = 0; i < arr.length; i++) {
    var item = arr[i];
    for (var key in item) {
        result[key] = (result[key] || 0) + item[key] // changed here
    }
}

console.log(result);
{X: 0, Y: 1, B: 3}

Simple solution: 简单的解决方案:

 const arr = [{X: -1}, {Y: 1}, {X: -4}, {B: 3}, {X: 5}]; let result = {}; for (let i = 0; i < arr.length; i++) { var item = arr[i]; for (var key in item) { if (result[key]) { // if key exists result[key] += parseInt(item[key]); } else { // if key doesn't exist result[key] = parseInt(item[key]); } } } console.log(result); 

a bit later but: 稍后,但是:

 const arr = [{X: -1}, {Y: 1}, {X: -4}, {B: 3}, {X: 5}]; const result = arr.reduce((acc, item) =>{ let currentKey = Object.keys(item)[0] return acc[currentKey] ? acc[currentKey] += item[currentKey] : acc[currentKey] = item[currentKey], acc }, {}) console.log(result) 

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

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