Have the following tree json object:
{
"Season1": {
"Title1": {
"a1": {
"val1": "100",
"val2": "200",
"val3": "300"
},
"a2": {
"val1": "100",
"val2": "200",
"val3": "300"
}
},
"Title2": {
"c1": {
"val1": "100",
"val2": "200",
"val3": "300"
},
"d2": {
"val1": "100",
"val2": "200",
"val3": "300"
}
}
}
}
Tried to format the json using the following function:
function Format(obj){
return Object.entries(obj).flatMap(([key, val]) => {
let o = { name: key}
if(Object.keys(val).some(function(k) {return typeof val[k] === 'object'})){
o['_children'] = Format(val)
} else {
Object.keys(val).map(function(a){
o[a] = val[a]
})
}
return [o]
})
}
That will return an array of nested objects by keys:
[
{
"name": "Season1",
"_children": [
{
"name": "Title1",
"_children": [
{
"name": "a1",
"val1": "100",
"val2": "200",
"val3": "300"
},
{
"name": "a2",
"val1": "100",
"val2": "200",
"val3": "300"
}
]
},
{
"name": "Title2",
"_children": [
{
"name": "c1",
"val1": "100",
"val2": "200",
"val3": "300"
},
{
"name": "d2",
"val1": "100",
"val2": "200",
"val3": "300"
}
]
}
]
}
]
The challenge is to calculate putting them on to the same level as well as adding subtotal of the bottom level keys, which are val1, val2, val3, in each parent levels recursively, .e.g. "Title1", "Title2", and "Season1", therefore after populating the output into a table can fill up the blank subtotal cells. And the children level should be indented with 4 white space depending on how deep the level is. The expected output should look like:
[
{"name": "Season1", "val1": 600, "val2": 800, "val3": 1200},
{"name": " Title1", "val1": 200, "val2": 400, "val3": 600},
{"name": " a1", "val1": "100", "val2": "200", "val3": "300"},
{"name": " a2", "val1": "100", "val2": "200","val3": "300"},
{"name": " Title2","val1": 400, "val2": 400, "val3": 600},
{"name": " c1", "val1": "100", "val2": "200", "val3": "300"},
{"name": " d2", "val1": "100", "val2": "200", "val3": "300"},
]
How to update the Format function for that purpose? Can someone share any thoughts or solution? Thanks!