扁平化路由中的children

本文介绍了一种使用递归方法遍历复杂树形结构数据的方法,包括仅获取叶子节点和获取所有节点的完整路径。通过具体示例展示了如何递归地处理每个节点,并拼接完整的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两种效果:

  1. 只取叶子
  2. 全部都要

思路:1 判断有子节点就递归,2传递res接收结果,3 把父path一层层传下去,使用args接收不定参数

let arr = [
  {
    path: '1',
    children: [
      { path: '/1.1', children: [{ path: '/1.1.1' }, { path: '/1.1.2 ' }] },
      { path: '/1.2 ' },
    ],
  },
  {
    path: '2',
    children: [
      { path: '/2.1', children: [{ path: '/2.1.1' }, { path: '/2.1.2 ' }] },
      { path: '/2.2 ' },
    ],
  },
  { path: '3', children: [{ path: '/3.1' }, { path: '/3.2 ' }] },
]

只取叶子

fun(arr)
function fun(arr) {
  let res = []
  funSub(arr, res, null)
  console.log(res)
}

function funSub(arr, res, ...args) {
  arr.forEach((item) => {
    if (item.children) {
      funSub(item.children, res, item, ...args)
    } else {
      let tmp = item.path
      if (args.length > 0) {
        args.forEach((arg) => {
          if (arg) {
            tmp = arg.path + tmp
          }
        })
      }
      res.push({ path: item.path, tmp })
    }
  })
}

效果

[
  { path: '/1.1.1', tmp: '1/1.1/1.1.1' },
  { path: '/1.1.2 ', tmp: '1/1.1/1.1.2 ' },
  { path: '/1.2 ', tmp: '1/1.2 ' },
  { path: '/2.1.1', tmp: '2/2.1/2.1.1' },
  { path: '/2.1.2 ', tmp: '2/2.1/2.1.2 ' },
  { path: '/2.2 ', tmp: '2/2.2 ' },
  { path: '/3.1', tmp: '3/3.1' },
  { path: '/3.2 ', tmp: '3/3.2 ' }
]

全部都要

fun(arr)
function fun(arr) {
  let res = []
  funSub(arr, res, null)
  console.log(res)
}

function funSub(arr, res, ...args) {
  arr.forEach((item) => {
    let tmp = item.path
    if (args.length > 0) {
      args.forEach((arg) => {
        if (arg) {
          tmp = arg.path + tmp
        }
      })
    }
    res.push({ path: item.path, tmp })
    if (item.children) {
      funSub(item.children, res, item, ...args)
    }
  })
}

效果

[
  { path: '1', tmp: '1' },
  { path: '/1.1', tmp: '1/1.1' },
  { path: '/1.1.1', tmp: '1/1.1/1.1.1' },
  { path: '/1.1.2 ', tmp: '1/1.1/1.1.2 ' },
  { path: '/1.2 ', tmp: '1/1.2 ' },
  { path: '2', tmp: '2' },
  { path: '/2.1', tmp: '2/2.1' },
  { path: '/2.1.1', tmp: '2/2.1/2.1.1' },
  { path: '/2.1.2 ', tmp: '2/2.1/2.1.2 ' },
  { path: '/2.2 ', tmp: '2/2.2 ' },
  { path: '3', tmp: '3' },
  { path: '/3.1', tmp: '3/3.1' },
  { path: '/3.2 ', tmp: '3/3.2 ' }
]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值