I have an array like below:
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'm trying to convert this data in a format where I can show this one in a table with total values for keys "val1", "val2" added in the top level of their corresponding top level keys ( ie name). The end result I'm expecting is something like this.
[
{
"name": "Top1",
// Only these two values will be extra
"val1": 2206, // "val1": 876 + "val1": 654 + "val1": 676
"val2": 4644, // "val1": 3456 + "val1": 300 + "val1": 888
"data": [
{
"name": "shahnshah",
"data": [
{
"name": "test1",
"values": {
"val1": 876,
"val2": 3456
}
}
]
}
]
},
{
// next object continued here
}
]
This way I want to able to show the sum of the values at the top and can eventually display this in a nested table.
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 } } ] } ] } ]; let newCollection=collection.reduce((a,c)=>{ c.val1=c.data.reduce((a1,c1)=>{ return a1+c1.data.reduce((aa,cc)=> aa+cc.values.val1,0);},0) c.val2=c.data.reduce((a1,c1)=>{ return a1+c1.data.reduce((aa,cc)=> aa+cc.values.val2,0);},0) a=[...a,c]; return a; },[]) console.log(newCollection);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.