2

js树的查找 - 通过子节点获取所有关联的父节点

 2 years ago
source link: https://www.fly63.com/article/detial/11502
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

更新日期: 2022-05-13阅读量: 34标签: 分享

扫一扫分享

树是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']

链接: https://www.fly63.com/article/detial/11502


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK