gpt4 book ai didi

javascript - 将嵌套数组内的对象数组分组并将其总数添加到新数组中

转载 作者:行者123 更新时间:2023-12-04 07:43:38 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





JavaScript - Sum the values of same ids of different objects in the array of objects

(9 个回答)


4 个月前关闭。




我有一组具有不同税率及其值(value)的对象。我正在尝试将具有相同税率的所有值合并为单个对象。下面是我的代码

const arr = [
{
"taxes": [
{
"name": "CGST 2.5%",
"total": 4.01,
},
{
"name": "SGST 2.5%",
"total": 4.01,
},
],
},
{
"taxes": [
{
"name": "CGST 6%",
"total": 10,
},
{
"name": "SGST 6%",
"total": 10,
},
],
},
{
"taxes": [
{
"name": "CGST 2.5%",
"total": 16.42,
},
{
"name": "SGST 2.5%",
"total": 16.42,
},
],
},
{
"taxes": [
{
"name": "CGST 2.5%",
"total": 0,
},
{
"name": "SGST 2.5%",
"total": 0,
},
],
},
{
"taxes": [
{
"name": "CGST 6%",
"total": 12,
},
{
"name": "SGST 6%",
"total": 12,
},
],
},
];

const result = arr.map(item => {
return Object.values(item.taxes.reduce((r, { name, total }) => {
(r[name] || (r[name] = [name, 0]))[1] += total;
return r;
}, {}));
})

console.log(result);

我已经搜索并获得了正在运行的 reduce 函数,但我无法使其与嵌套数组一起使用。
请以我的能力容忍,因为我根本不熟悉 reduce 函数的工作原理。
我想要的它会返回一个新的数组,例如
{ "CGST 2.5%": 20.43, "SGST 2.5%": 20.43, "CGST 6%": 22, "SGST 6%": 22 }

最佳答案

我能想到的更简单的解决方案:

const result = {}
arr.forEach(el => {
el.taxes.forEach(tax => {
result[tax.name] = (result[tax.name] || 0)+ tax.total
})
})
const solution = Object.entries(result).map(el => ({name: el[0], total: el[1]}))
console.log(solution)

关于javascript - 将嵌套数组内的对象数组分组并将其总数添加到新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67315453/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com