Having an issue with recursion regarding the following data:
let data = {
label: "Root",
datasets: [
{
label: "Parent 1"
datasets: [
{
label: "Child 1",
dataMax: 100,
datasets: 30
},
{
label: "Child 2",
dataMax: 30,
datasets: 30
}
]
},
{
label: "Parent 2",
dataMax: 50,
datasets: 30
}
]
};
The goal is to add a dataMax
property and values in every parent that does not have one, and for parents with multiple children, the dataMax
should contain the total of its children's values.
Note that the depth and length of data
are variable.
Here is what has been attempted so far:
let data = {
label: "Root",
datasets: [
{
label: "Parent 1",
datasets: [
{
label: "Child 1",
dataMax: 100,
datasets: 30
},
{
label: "Child 2",
dataMax: 30,
datasets: 30
}
]
},
{
label: "Parent 2",
dataMax: 50,
datasets: 30
}
]
};
let setDatas = function(x, i, p){
if (x == undefined) {
console.log("--- This is x==undefined ---");
return 1;
} else if (Array.isArray(x.datasets)) {
console.log("-------------- " + x.label + ", datasets[" + [i] + "]:");
console.log(x.datasets[i]);
return setDatas(x.datasets[i], i, x);
} else {
console.log("It's not an Array");
++i;
return setDatas(p, i, p);
}
}
setDatas(data, 0);
Managed to reach the desired depth but struggling to return to the root. It feels like something is missing. What could be wrong?
Expected Output:
let data = {
label: "Root",
dataMax: 180, // Total sum from Parent 1 and 2 dataMax values
datasets: [
{
label: "Parent 1",
dataMax: 130, // Total sum of "Child 1" and "Child 2" dataMax values
datasets: [
{
label: "Child 1",
dataMax: 100,
datasets: 30
},
{
label: "Child 2",
dataMax: 30,
datasets: 30
}
]
},
{
label: "Parent 2",
dataMax: 50,
datasets: 30
}
]
};
Appreciate any assistance or further information required. Thank you.