首页 > 解决方案 > 如何检查对象嵌套了多少层?

问题描述

假设我有以下对象:

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

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

我已经搜索过,唯一能找到的类似问题是这个问题,但它对我不起作用,而且似乎也很过时。

标签: javascript

解决方案


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

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))


推荐阅读