如何找到对象的最深层级?

如下数组,我想找到最深层级('sub_menus'为空为止),一共多少层

var menus = [{
    name: '1',
    sub_menus: [{
        name: '11',
        sub_menus: [{
            name: '111',
            sub_menus: []
        }]
    }]
}, {
    name: '2',
    sub_menus: [{
        name: '22',
        sub_menus: [{
            name: '222',
            sub_menus: [{
                name: '2222',
                sub_menus: []
            }, {
                name: '2222-1',
                sub_menus: []
            }]
        }]
    }]
},
{
    name: '3',
    sub_menus: [{
        name: '33',
        sub_menus: [{
            name: '333',
            sub_menus: []
        }]
    }]
}];
阅读 4k
3 个回答
console.log('最大层级:', countTree(menus)); // => 4

function countTree (list) {
  for(var a = 0, max = 0; a < list.length; a++) {
    max = Math.max(max, countOne(list[a]))
  }
  return max
}

function countOne (item, deep) {
  deep = (deep || 0) + 1
  var max = deep;
  if(getType(item) === 'Object' && getType(item.sub_menus) === 'Array' && item.sub_menus.length) {
    for(var a = 0; a < item.sub_menus.length; a++) {
      max = Math.max(countOne(item.sub_menus[a], deep), max)
    }
  }
  return max
}

function getType (data) {
  return Object.prototype.toString.call(data).replace(/(.*\s)|.$/g, '');
}

可以使用深度优先搜索

function deepSearch(menus, count = 0) {
      console.log(menus, count)
      if(!menus && !menus.length) {
        return count
      }
      let maxCount = -1
      for(let i = 0; i < menus.length; i++) {
        if(menus[i]['sub_menus']) {
          count = deepSearch(JSON.parse(JSON.stringify(menus[i].sub_menus)), ++count);
          if(count > maxCount) {
            maxCount = count
            count = 0
          }
        }
      }
      return maxCount == -1 ? count : maxCount
    }
    console.log(deepSearch(menus, 0))

随便口胡个 DFS 就好了,写个递归函数,俩参数,一个对象,一个深度。
到底了:返回深度(递归出口)
没到底:开始对每个孩子递归,递归时深度加 1,返回最深分支的深度。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题