根据匹配键添加对象值

时间:2019-08-23 16:42:14

标签: javascript

我有一个对象数组,我正在尝试像键一样组合并添加值。因此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);

我希望X为0,但返回5。

5 个答案:

答案 0 :(得分:1)

您可以将Array.prototype.reduceObject.entries结合使用以按键分组,以求和。

以下示例(请查看评论以获取更多详细信息):

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

答案 1 :(得分:1)

您可以通过抓住键并为添加的先前值分配当前值来减少每个项目(对象)。

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

结果

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

趣味高尔夫实验

我通过使用扩展运算符将10个字节保存为Object.assign(o,{[k]:(o[k]||0)+e[k]})({...o,[k]:(o[k]||0)+e[k]})

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

答案 2 :(得分:0)

在此更改了内部循环,以便我们访问密钥(如果存在),将其使用;否则将其初始化为零。然后添加值。

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}

答案 3 :(得分:0)

简单的解决方案:

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

答案 4 :(得分:0)

过一会儿,但是:

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)