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

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

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++
}

 path设置为数组方式 

export function assembleTree(nodes, parent, depth) {
    if(!depth) depth = 0
    nodes.forEach(n => {
        let path = parent.length?parent.concat(n.path):[n.path] // 数组记录path
        n.meta = {name: n.name, role: n.path, path: path}
        if (n.children && n.children instanceof Array) {
            tree.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"}}]

对你有帮助就点个赞 

你可能感兴趣的:(工具,js)