How to check the depth of an object?
javascript, object, recursion
Solution
Well, here you go buddy, a function that does exactly what you need!
utils.depthOf = function(object) {
var level = 1;
for(var key in object) {
if (!object.hasOwnProperty(key)) continue;
if(typeof object[key] == 'object'){
var depth = utils.depthOf(object[key]) + 1;
level = Math.max(depth, level);
}
}
return level;
}
A lot easier than we thought it would be. The issue was how it was incremented, it shouldn't have been recursively adding, rather getting the bottom-most and adding one, then choosing the max between two siblings.
Problem
I'm working on a permissions system with variable depth; depending on the complexity of a page, there could be more or less levels. I searched StackOverflow to find if this has been asked before, couldn't find it. If I have this object: ``` {foo:{bar:{baz : 'baa'}}} ``` I need it to return 3, it has 3 levels to it. With this object: ``` {abc: 'xyz'} ``` It would have to be 1. This is what I have so far: ``` utils.depthOf = function(object, level){ // Returns an int of the deepest level of an object level = level || 1; var key; for(key in object){ if (!object.hasOwnProperty(key)) continue; if(typeof object[key] == 'object'){ level++; level = utils.depthOf(object[key], level); } } return level; } ``` The problem is it counts sister elements too. It's actually not getting depth, it's counting all members of an object.