I have a collection array that looks like this:
const collection = [
{
"name": "Top1",
"data": [
{
"name": "shahnshah",
"data": [
{
"name": "test1",
"values": {
"val1": 876,
"val2": 3456
}
}
]
},
{
"name": "Alex",
"data": [
{
"name": "test1",
"values": {
"val1": 654,
"val2": 300
}
},
{
"name": "test2",
"values": {
"val1": 676,
"val2": 888
}
}
]
}
]
},
{
"name": "Top2",
"data": [
{
"name": "shahnshah",
"data": [
{
"name": "test1",
"values": {
"val1": 111,
"val2": 300
}
}
]
},
{
"name": "Alex",
"data": [
{
"name": "test1",
"values": {
"val1": 100,
"val2": 150
}
},
{
"name": "test2",
"values": {
"val1": 600,
"val2": 50
}
}
]
}
]
}
];
I want to transform this data so I can display it in a table format with the total values for keys "val1" and "val2" added at the top level under their corresponding key (e.g. name). The expected end result should look like this.
[
{
"name": "Top1",
// Only these two values will be extra
"val1": 2206, // sum of 876 + 654 + 676
"val2": 4644, // sum of 3456 + 300 + 888
"data": [
{
"name": "shahnshah",
"data": [
{
"name": "test1",
"values": {
"val1": 876,
"val2": 3456
}
}
]
}
]
},
{
// next object continued here
}
]
This approach allows me to show the sum of values at the top and eventually present it in a nested table.