javascript 如何检查物体的深度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13523951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 19:02:29  来源:igfitidea点击:

How to check the depth of an object?

javascriptobjectrecursion

提问by Kavi Siegel

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.

我正在研究具有可变深度的权限系统;根据页面的复杂程度,可以有更多或更少的级别。我搜索了 StackOverflow 以查找之前是否有人问过这个问题,但找不到。

If I have this object:

如果我有这个对象:

{foo:{bar:{baz : 'baa'}}}

I need it to return 3, it has 3 levels to it.

我需要它返回 3,它有 3 个级别。

With this object:

有了这个对象:

{abc: 'xyz'} 

It would have to be 1.

它必须是 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.

问题是它也计算姐妹元素。它实际上并没有获得深度,而是在计算对象的所有成员。

回答by Kavi Siegel

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.

比我们想象的要容易得多。问题是它是如何递增的,它不应该递归添加,而是获取最底层并添加一个,然后在两个兄弟姐妹之间选择最大值。

回答by Yippee

We can use the reg:

我们可以使用 reg:

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

回答by DonFuchs

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;
}