js树的查找 - 通过子节点获取所有关联的父节点
树是JS中非常常见的数据结构。知识库目录,侧边栏菜单,字典目录,企业组织架构等都可能会用到树的操作。
实现根据节点id查找关联的父节点函数familyTree。我们先定义一个空函数,该函数需要接收3个参数:树形结构数组tree,节点id,节点信息配置obj。obj用于配置id和children等字段,因为这是一个通用函数,我们需要应对后端开发者使用的children和id字段可能存在的不统一问题。
代码实现:
const familyTree=function(tree,id,obj={}){
let temp = []
obj.children = obj.children || 'children'
obj.parentId = obj.parentId || 'pid'
obj.id = obj.id || 'id'
let forFn = (arr, id)=>{
for (let i = 0; i < arr.length; i++) {
let item = arr[i]
if (item[obj.id] === id) {
temp.push(obj.key ? item[obj.key] : item)
forFn(tree, item[obj.parentId])
break
} else {
if (item[obj.children]) {
forFn(item[obj.children], id)
}
}
}
}
forFn(tree, id)
return temp
}使用:
const tree = [{
id: 1,
label: 'test1',
children: [{
id: 2,
pid:1,
label: 'test1-1',
children: [{
id: 3,
pid:2,
label: 'test1-1-1'
},
{
id: 4,
pid:2,
label: 'test1-1-2',
children: [{
id: 5,
pid:4,
label: 'test1-1-1-1'
}]
}
]
}]
}]
let data=familyTree(tree,5)
console.log(data)
打印结果如下:
0: {id: 5, pid: 4, label: 'test1-1-1-1'}
1: {id: 4, pid: 2, label: 'test1-1-2', children: Array(1)}
2: {id: 2, pid: 1, label: 'test1-1', children: Array(2)}
3: {id: 1, label: 'test1', children: Array(1)}如果我只需要获取lable的值,我们可以这样:
let data=familyTree(tree,5,{key:'label'})
console.log(data)
// ['test1-1-1-1', 'test1-1-2', 'test1-1', 'test1']本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!