javascript - 对键值对匹配的嵌套对象中的值求和

标签 javascript arrays object

我在尝试对对象内的值求和时遇到问题。

给定以下数组:

const data = [
  {
    id: "tom",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
  {
    id: "tom",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
  {
    id: "dick",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
  {
    id: "harry",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
  {
    id: "harry",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
];

我需要对值对象中 id 匹配的每个数字求和, 给出以下结果:

const result = [
  {
    id: "tom",
    values: { ten: 20, twenty: 40, thirty: 60 },
  },
  {
    id: "dick",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
  {
    id: "harry",
    values: { ten: 20, twenty: 40, thirty: 60 },
  }
];

有没有简单的方法可以实现这一点?

也许是reduce和map的某种组合?

最佳答案

使用Array#reduce积累所需的数据。为此,迭代对象并查看新累积的(开始时为空)结果对象中是否存在具有此 id 的属性。如果没有,请创建一个并在其中添加对象。否则,将值对象的每个属性的值添加到对象中。

最后一次使用Object#values从对象中获取所需的数组。

const data = [
  {
    id: "tom",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
  {
    id: "tom",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
  {
    id: "dick",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
  {
    id: "harry",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
  {
    id: "harry",
    values: { ten: 10, twenty: 20, thirty: 30 },
  },
];

let res = Object.values(data.reduce((acc, cur) => {
    if (!acc.hasOwnProperty(cur.id)) {
        acc[cur.id] = { id: cur.id, values: cur.values};
    } else {
        Object.entries(cur.values).forEach(([key,value]) => acc[cur.id].values[key] += value);
    }
    return acc;
}, {}));

console.log(res);

关于javascript - 对键值对匹配的嵌套对象中的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63641050/

相关文章:

javascript - 是否有不实现 Timers 接口(interface)的 javascript 引擎(运行时)

c# - 查找一行中具有相同值的单元格数,然后存储这些坐标

javascript - 探索并获取多级对象的属性

javascript - 如何将 JS 键控对象转换为键控数组,同时跳过未定义?

javascript - 使用闭包编译器缩小包含 Jinja2 表达式的 JavaScript 代码

javascript - win.open后更改外部页面上的id值

javascript - jQuery 正则表达式返回意外结果

php - 在函数中使用 PDO 返回一些值

javascript - 如何将数组从 PHP/MySQL 转换为 Javascript

java - 如何在Java中打印List对象元素?