Here is the input arr:
const arr = [
{ id: 1 },
{ id: 11, parent_id: 1, total: 2 },
{ id: 12, parent_id: 1 },
{ id: 121, parent_id: 12, total: 1 },
{ id: 122, parent_id: 12, total: 2 }
];
I need to format the arrays. Use recursive function, the value of "total" in parent node = sum all the value of "total" in childs node. The expected output will be:
[
{ id: 1 , total: 5},
{ id: 11, parent_id: 1, total: 2 },
{ id: 12, parent_id: 1, total: 3 },
{ id: 121, parent_id: 12, total: 1 },
{ id: 122, parent_id: 12, total: 2 }
];
2
Answers
ok so for this you need to consider following things:
If only leaf nodes contain
total
:Otherwise find leaf nodes (this is also for updating parents when some leaf is changed):