我在尝试对对象内的值求和时遇到问题。
给定以下数组:
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/