js,ts 便利树形结构每个节点

这篇博客主要展示了如何通过JavaScript实现递归遍历一个包含多级children的对象数组,生成路由配置。示例中,函数`getAllList`接收一个包含路由信息的对象数组,如果当前项有children并且不为空,则递归调用自身,最终返回完整的路由配置结构。这个过程涉及到前端开发中的路由管理和数据结构操作。
摘要由CSDN通过智能技术生成

 调用函数时传递的值

let resultArr = getAllList([
    {
      name: '一级路由',
      path: 'first/',
      component: 'first',
      children: [
        {
          name: '二级路由',
          path: 'first/child',
          component: 'firstchild',
          children: [
            {
              name: '三级路由',
              path: 'first/child/child',
              component: 'firstchildchild',
            },
          ],
        },
        {
          name: '二级路由',
          path: 'first/child',
          component: 'firstchild',
          children: [
            {
              name: '三级路由',
              path: 'first/child/child',
              component: 'firstchildchild',
            },
          ],
        },
        {
          name: '二级路由',
          path: 'first/child',
          component: 'firstchild',
          children: [
            {
              name: '三级路由',
              path: 'first/child/child',
              component: 'firstchildchild',
            },
          ],
        },
      ],
    },
    {
      name: '二级路由',
      path: 'second/',
      component: 'second',
      children: [
        {
          name: '二级路由',
          path: 'two/child',
          component: 'towchild',
          children: [
            {
              name: '三级路由',
              path: 'first/child/child',
              component: 'firstchildchild',
            },
          ],
        },
      ],
    },
  ])

  console.log(resultArr, '这里是resultArr')

执行过程:如果一直由children 那么就一直调用自身,直到最后一层则返回对应的值

 

const getAllList = (currentArr: any) => {
  let result = currentArr.map((item: any) => {
    if (item.children && item.children.length && item.children[0]) {
      item.children = getAllList(item.children)

      return {
        name: item.name,
        path: item.path,
        component: item.component,
        children: item.children,
        role: '超人',
      }
    } else {
      return {
        name: item.name,
        path: item.path,
        component: item.component,
      }
    }
  })
  return result
}

这里是返回值

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值