[英]how can I either move or calculate the sum of a deeply nested object's properties to the top level in an object array
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).我正在尝试以一种格式转换此数据,我可以在表格中显示此数据,并将键“val1”、“val2”的总值添加到其对应的顶级键(即名称)的顶级中。 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.