多级数组返回全部排列和指定排列

问题来源于antd中,使用menu时,多级菜单(大于二级时),设置点击一个菜单收起其他菜单,openKeys必须设置为从父到子的所有key的数组。详情请见:实现antd中menu多级菜单(大于二级)点击菜单,收起其他菜单

const arr = [
  {
    key: 1,
    children: [
      {
        key: 2,
        children: [
          { key: 3 },
          { key: 4 }
        ]
      },
      { key: 5 }
    ]
  },
  {
    key: 6,
    children: [
      { key: 7 },
      { key: 8 }
    ]
  }
]

获取全部排列
对于这样这样一个数组,我们怎么取到下面全部的排列呢?

// [1, 2, 3]
// [1, 2, 4]
// [1, 5]
// [6, 7]
// [6, 8]
function findAllPath (array, path = []) {
  if (!array) return []
  for (const data of array) {
    path.push(data.key)
    if (!data.children) { // 不存在子数组即已完成
      console.log(path) 
    }
    if (data.children) { // 存在子数组递归循环
      const findChildren = findAllPath(data.children, path)
    }
    path.pop()
  }
}

获取指定排列
需求中我不需要获取全部的排列,只需要获取到指定的排列。比如我需要获取到key为4的排列:

function findSpecPath (array, func, path = []) {
  if (!array) return []
  for (const data of array) {
    path.push(data.key)
    if (func(data)) { // 判断是否符合指定条件
      return path
    }
    if (data.children) {
      const findChildren = findSpecPath(data.children, func, path)
      if (findChildren.length) return findChildren
    }
    path.pop()
  }
  return []
}

执行这个方法

console.log(findSpecPath(arr, data => data.key === 4)) // 打印执行结果
//执行结果 [1, 2, 4]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容