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.

Edit
Report