嵌套数组对象扁平化

91 阅读1分钟

在部署一个导航菜单时需要获取我点击的那一项的数据,但是因为数组对象里有嵌套关系,没办法直接通过遍历进行获取,在网上查了一下,发现可以用递归将嵌套关系扁平化,感觉很有用就想记录下来

//数组对象
const items = reactive([
    {
      key: 'home',
      label: '首页',
      title: '首页',
      path: '/home'
    },
    {
      key: 'sub1',
      label: '系统管理',
      title: '系统管理',
      children: [
        {
          key:'system1',
          label: '用户管理',
          title: '用户管理',
          path: '/home/system/user'
        }, {
          key: 'system2',
          label: '职位管理',
          title: '职位管理',
          path: '/home/system/role'
        }
      ]
    },
    {
      key: 'sub2',
      label: '接口文档',
      title: '接口文档',
      children: [
        {
          key: 'apl',
          label: 'Aplfox',
          title: 'Aplfox',
          path:  '/home/Aplfox'
        }
      ]
    },
function flatArray(arr) {
  return arr.reduce((result, item) => {
    return result.concat(item, (Array.isArray(item.children) ? flatArray(item.children) : []))
  },[])
}
let newItems = flatArray(items)

这样就可以把数组对象的每一项拿出来放在这个新的 newItems 数据里面,就可以用这个新数据来遍历过滤了。