How to check the depth of an object?

后端 未结 3 2042
我在风中等你
我在风中等你 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:08

    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.

    0 讨论(0)
  • 2020-11-29 08:17

    We can use the reg:

    function getHowManyLevel(obj) {
      let res = JSON.stringify(obj).replace(/[^{|^}]/g, '')
      while (/}{/g.test(res)) {
        res = res.replace(/}{/g, '')
      }
      return res.replace(/}/g, '').length
    }

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题