Suppose I have the following JSON:
{
"id": "foo",
"list": [
{
"id": "A",
"list": [
{
"id": "B",
"list": [
{
"id": "C",
"list": [
{
"id": "D",
"list": []
},
{
"id": "E",
"list": []
}
]
},
{
"id": "F",
"list": []
},
{
"id": "G",
"list": [
{
"id": "H",
"list": []
},
{
"id": "I",
"list": []
},
{
"id": "J",
"list": []
}
]
}
]
},
{
"id": "K",
"list": []
}
]
},
{
"id": "L",
"list": [
{
"id": "M",
"list": []
}
]
},
{
"id": "N",
"list": []
},
{
"id": "O",
"list": [
{
"id": "P",
"list": [
{
"id": "Q",
"list": []
},
{
"id": "R",
"list": []
},
{
"id": "S",
"list": []
},
{
"id": "T",
"list": [
{
"id": "U",
"list": []
}
]
},
{
"id": "V",
"list": [
{
"id": "W",
"list": [
{
"id": "X",
"list": []
},
{
"id": "Y",
"list": []
},
{
"id": "Z",
"list": []
}
]
}
]
}
]
}
]
}
]
}
My question is: How could I count each of the childs and append this number into a property of each object?
Example:
Regarding this, the "C" object should have a property, let's name it "allBelow", containing the number 2. The "W" object containing 3, and the "V" object containing 4. And so on, for each object.
I wonder that some recursive function could do this job but I'm not achieving it.
Could you please help me?
Bests,
var myObj = {"id":"foo","list":[{"id":"A","list":[{"id":"B","list":[{"id":"C","list":[{"id":"D","list":[]},{"id":"E","list":[]}]},{"id":"F","list":[]},{"id":"G","list":[{"id":"H","list":[]},{"id":"I","list":[]},{"id":"J","list":[]}]}]},{"id":"K","list":[]}]},{"id":"L","list":[{"id":"M","list":[]}]},{"id":"N","list":[]},{"id":"O","list":[{"id":"P","list":[{"id":"Q","list":[]},{"id":"R","list":[]},{"id":"S","list":[]},{"id":"T","list":[{"id":"U","list":[]}]},{"id":"V","list":[{"id":"W","list":[{"id":"X","list":[]},{"id":"Y","list":[]},{"id":"Z","list":[]}]}]}]}]}]};
function count(obj) {
var c = obj.list.length;
c += obj.list.reduce((a, e) => a + count(e), 0);
obj.count = c; // assign the count after counting the subobjects.
return c; // return the count to be used by parent objects
}
count(myObj);
console.log(myObj);