I have been at this all day, trying to write a recursive function in Javascript to get the sizes. I need some help :/
Basically, my JSON object contains hierarchical categories/subcategories. I’d like to determine the size of each category/subcategory.
Here is a simple demonstration: http://pastehtml.com/view/bkpzzlabs.html
I’d like to take the JSON on the left and get the HTML on the right. Perhaps I’ve just been staring at this computer monitor for too long because for the life of me I can’t figure this out.
Thanks so much for your help.
The right-hand side of your "demonstration" suggests that you don’t just want to recursively count the total number of endpoints (or "leafs") in your JSON; you want to know the recursive size for each category (non-leaf node) in the tree. The key here is that the nodes in between the leafs and the root don’t count.
Try this:
This function will modify the original object, so that a new key
'num_children'is added to each non-leaf node in the tree. The function returns the total number of leaf nodes in all of theparent‘s descendants. Note that it’s also perfectly possible to call this function on a subset of your object.Here is a live demo: http://jsfiddle.net/PPvG/CXXaB/