I have this object
[
{
"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
}
]
I have been trying to sum the worthAmountEGP
based on multiple conditions (same year and same term )
this is what I have been trying
const transformed = Object.values(
aa.reduce((acc, { term, worthAmountEGP, year }) => {
acc[term] = acc[term] || { term, worthAmountEGP: 0 };
acc[term].worthAmountEGP += worthAmountEGP;
return acc;
}, {})
);
this is my output
Transformed: [
{ term: 1, worthAmountEGP: 5000000 },
{ term: 2, worthAmountEGP: 3200000 },
]
my desired output is
[
{ 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},
]