【问题标题】:How can I check how many levels deep an object is nested?如何检查对象嵌套了多少层?
【发布时间】:2019-08-16 21:42:14
【问题描述】:

假设我有以下对象:

const myObj = {
  id: 1,
  children: [
    {
      id: 2,
      children: [
        {
          id: 3
        }
      ]
    },
    {
      id: 4,
      children: [
        {
          id: 5,
          children: [
            {
              id: 6,
              children: [
                {
                  id: 7,
                }
              ]
            }
          ]
        }
      ]
    },
  ]
}

如何判断物体的深度?例如,上面的对象将是 4 层深。

我已经搜索过 SO,我唯一能找到的类似内容是 this question,但它对我不起作用,而且似乎也非常过时。

【问题讨论】:

  • 递归将children 作为根对象传递
  • “它对我不起作用” - 这是对您遇到的问题的非常彻底的解释......; “也似乎很过时” - 而这个假设究竟基于什么?
  • 您引用的帖子已经拥有创建自己的解决方案所需的一切。

标签: javascript


【解决方案1】:

找到了答案。万一将来有人遇到这种情况:

const myObj={id:1,children:[{id:2,children:[{id:3}]},{id:4,children:[{id:5,children:[{id:6,children:[{id:7,}]}]}]},]}

function determineDepthOfObject(object) {
  let depth = 0;
  if (object.children) {
    object.children.forEach(x => {
      let temp = this.determineDepthOfObject(x);
      if (temp > depth) {
        depth = temp;
      }
    })
  }
  return depth + 1;
}

console.log(determineDepthOfObject(myObj))

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 2019-04-08
    • 2021-05-05
    • 2013-04-06
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多