提问人:Mohamed Khalifa 提问时间:9/26/2023 更新时间:9/26/2023 访问量:38
根据多个条件对对象数组中的值求和
sum the value inside array of objects based on multiple conditions
问:
我有这个对象
[
{
"year": 2020,
"term": 1,
"worthAmountEGP": 0
},
{
"year": 2020,
"term": 2,
"worthAmountEGP": 300000
},
{
"year": 2021,
"term": 1,
"worthAmountEGP": 0
},
{
"year": 2021,
"term": 2,
"worthAmountEGP": 1000000
},
{
"year": 2021,
"term": 1,
"worthAmountEGP": 0
},
{
"year": 2021,
"term": 2,
"worthAmountEGP": 400000
},
{
"year": 2022,
"term": 1,
"worthAmountEGP": 0
},
{
"year": 2022,
"term": 2,
"worthAmountEGP": 1000000
}
]
我一直在尝试根据多个条件(同一年份和同一期限)进行求和worthAmountEGP
这就是我一直在努力的
const transformed = Object.values(
aa.reduce((acc, { term, worthAmountEGP, year }) => {
acc[term] = acc[term] || { term, worthAmountEGP: 0 };
acc[term].worthAmountEGP += worthAmountEGP;
return acc;
}, {})
);
这是我的输出
Transformed: [
{ term: 1, worthAmountEGP: 5000000 },
{ term: 2, worthAmountEGP: 3200000 },
]
我想要的输出是
[
{ term: 1, worthAmountEGP: 0, year:2020 },
{ term: 2, worthAmountEGP: 300000, year:2020 },
{ term: 1, worthAmountEGP: 0, year:2021},
{ term: 2, worthAmountEGP: 1400000, year:2021},
{ term: 1, worthAmountEGP: 0, year:2022},
{ term: 2, worthAmountEGP: 1000000, year:2022},
]
答:
2赞
Ori Drori
9/26/2023
#1
将数组简化为 ()。通过组合 和 创建 .如果 Map 没有 ,请设置当前对象的副本。如果确实存在,则将 添加到当前值 中。在 Map 的迭代器上使用获取数组:Map
acc
key
year
term
key
worthAmountEGP
Array.from()
.values()
const data = [{"year":2020,"term":1,"worthAmountEGP":0},{"year":2020,"term":2,"worthAmountEGP":300000},{"year":2021,"term":1,"worthAmountEGP":0},{"year":2021,"term":2,"worthAmountEGP":1000000},{"year":2021,"term":1,"worthAmountEGP":0},{"year":2021,"term":2,"worthAmountEGP":400000},{"year":2022,"term":1,"worthAmountEGP":0},{"year":2022,"term":2,"worthAmountEGP":1000000}]
const result = Array.from(data.reduce(
(acc, o) => {
const key = `${o.year}---${o.term}`
if(!acc.has(key)) acc.set(key, { ...o })
else acc.get(key).worthAmountEGP += o.worthAmountEGP
return acc
}, new Map()
).values())
console.log(result)
评论