How to check the depth of an object?

后端 未结 3 2054
我在风中等你
我在风中等你 2020-11-29 07:53

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

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 08:21

    This should do it, if you wanna keep it short:

    function maxDepth(object) {
        if (typeof object !== "object" || object === null) {
            return 0;
        }
    
        let values = Object.values(object);
    
        return (values.length && Math.max(...values.map(value => maxDepth(value)))) + 1;
    }
    

提交回复
热议问题