I have a data like this :
const fund =
[
{
id: 1234,
totalAmount: 0,
data:
[
{
id: 1234,
amount: 4000
},
{
id: 1234,
amount: 3000
}
]
},
{
id: 12345,
totalAmount: 0
},
{
id: 123456,
totalAmount: 0
data:
[
{
id: 123456,
amount: 3000
},
{
id: 123456,
amount: 5000
}
]
}
]
I want to sum the amount
inside of data
each id to a key called totalAmount
. But not all the parent id
have data
key.
here’s my desired output :
const fund =
[
{
id: 1234
data:
[
{
id: 1234,
amount: 4000
},
{
id: 1234,
amount: 3000
}
],
totalAmount: 7000
},
{
id: 12345,
totalAmount: 0
},
{
id: 123456,
data:
[
{
id: 123456,
amount: 3000
},
{
id: 123456,
amount: 5000
}
],
totalAmount: 8000
}
]
I was trying with this code :
fund.forEach((elA, i) => {
if (elA.data) {
const total = funders[i].data.reduce((acc, curr) => {
acc += parseInt(curr.loanAmount.replace(/./g, ''))
return acc
})
}
})
But it’s not summing like i want.
Where’s my mistake ?
Please ask me if you need more information if it’s still not enough to solve that case.