js递归树结构并且加入path路径来为每个节点加入定位信息

本文介绍了一种高效确定树形结构中某项及其所有父级节点路径的方法,通过递归遍历实现,适用于多种应用场景,如文件系统、组织架构等。提供两种路径设置方式:数组形式和#号拼接形式。

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

有时候树形结构需要确定某一项它的具体路径(它的所有父级节点),为提高效率和减少代码,可以在树结构的遍历时确定路径path操作,以下代码就实现了此功能(注意:此代码确定path路径是在meta对象中的那个): 

treeUtils.js assembleTree方法二选一

  path设置为数组方式 

// 2022-08-30更新加入pathKey
export function assembleTree (nodes, parent, depth, pathKey) {
    if (!depth) depth = 0
    if (!pathKey) pathKey = 'id'
    nodes.forEach(n => {
        const path = parent.length ? parent.concat(n[pathKey]) : [n[pathKey]] // 数组记录path
        n.meta = { name: n.name, role: n[pathKey], path: path, depth }
        if (n.children && n.children instanceof Array) {
            assembleTree(n.children, path, depth + 1, pathKey)
        }
    })
    if (depth === 0) {
        return nodes
    }
}
// 使用案例 assembleTree(this.treeData, [], 0, 'id')

path设置为#号拼接方式 

export function assembleTree(nodes, parent, depth) {
  if(!depth) depth = 0
  nodes.forEach(n => {
    let path = parent?parent+'#'+n.path:n.path // 拼接path
    n.meta = {title: n.title, role: n.path, path: path}
    if (n.children && n.children instanceof Array) {
      assembleTree(n.children, path, depth)
    }
  })
  if (depth === 0) {
    return nodes
  }
  depth++
}

测试数据

[
  {title: 'a', path: 'a', children: [{title: 'a1', path: 'a1'}, {title: 'a2', path: 'a2'}]},
  {title: 'c', path: 'c'},
]

测试结果

[{"title":"a","path":"a","children":[{"title":"a1","path":"a1","meta":{"title":"a1","role":"a1","path":"a#a1"}},{"title":"a2","path":"a2","meta":{"title":"a2","role":"a2","path":"a#a2"}}],"meta":{"title":"a","role":"a","path":"a"}},{"title":"c","path":"c","meta":{"title":"c","role":"c","path":"c"}}]

对你有帮助就点个赞 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值