I\'m trying to write a function that will loop through my object and return the level depth of the object.
For example, if I ran the function on this object:
I have changed your code a bit to work as you want it to:
function getDepth(node, depth = 0) {
if (!!node.children && node.children.length > 0) {
var childDepths = [];
depth++;
for (var i = 0; i < node.children.length; i++) {
childDepths.push(getDepth(node.children[i]));
}
return depth + Math.max(...childDepths);
}
return depth;
}
var depth = getDepth(root);
console.log('currentMaxDepth', depth);
console.log('root', root);
The trick is to measure depths of siblings on the same level and than pick the deepest of them. Here's also a jsfiddle: https://jsfiddle.net/2xk7zn00/