I've got a data set simplified to the following
var data = {
foo: 'bar'
children: [
{
foo: 'bar'
children: [
{ foo: 'bar' }, // count
{ foo: 'bar' }, // count
{
foo: 'bar'
children: [
{ foo: 'bar' }, // count
{ foo: 'bar' }, // count
]
},
{ foo: 'bar' }, // count
]
},
{
// etc
}
]
}
There's a lot more of it than that. Any number of objects below nested.
{
foo: 'bar'
children: []
}
I want to be able to calculate the total 'last children' of any 'node' in the structure. So far I have written a quick script that will work it out from the top level using a counter variable scoped outside of the recursing function - but that stop it being re-usable.
var total = 0;
var countLastChildren = function(object) {
if(object.children) {
object.children.forEach(function(el){
countLastChildren(el);
});
} else {
total++;
}
}
countLastChildren(data);
console.log(total);
I can't quite get my head round how to scope the counter inside countLastChildren() to allow it to return a value and make it re-usable by passing in different objects or objects nested within my main structure.
Any ideas? Thanks
datais the structure shown, what would be the desired result fromcountLastChildren(data)? 7 (all the children of the top-most level), or 2 (just the lowest level children), or...?