1.获取某个节点的所有父节点:
getAllParentNodes(list, id) {
for(let i in list) {
if(list[i].resourcesId === id) {
return [list[i]].filter(v => v.resourcesId !== id)
}
if(list[i].children?.length > 0) {
let node = this.getAllParentNodes(list[i].children, id)
if(node) return node.concat(list[i]).filter(v => v.resourcesId !== id)
}
}
},
2.获取某个节点的兄弟节点:
getBrotherNodes(list, id) {
for(let i in list) {
if(list[i].resourcesId === id) {
return list.filter(v => v.resourcesId !== id)
}
if(list[i].children?.length > 0) {
let node = this.getBrotherNodes(list[i].children, id)
if(node) return node.filter(v => v.resourcesId !== id)
}
}
},
3.获取某个节点的所有子节点:
getAllChildrenNodes(list, id, arr = []) {
for(let i in list) {
if(list[i].resourcesId === id) {
arr.push(list[i])
if(list[i].children?.length > 0) {
this.getChild(list[i].children, arr)
}
}else {
if(list[i].children?.length > 0) {
this.getAllChildrenNodes(list[i].children, id, arr)
}
}
}
return arr.filter(v => v.resourcesId !== id)
},
getChild(list, arr) {
list.forEach(v => {
arr.push(v)
if(v.children) {
getChild(v.children, arr)
}
})
},
4.根据id查找节点
// 根据id查找节点
findNodeById (nodes, id, idName = 'setKey', childrenName = 'children') {
for (const node of nodes) {
console.log(node)
if (node[idName] === id) {
return node
}
if (node[childrenName]) {
const foundNode = this.findNodeById(node.children, id, idName, childrenName)
if (foundNode) {
return foundNode
}
}
}
return null
},
5.数据:
let list = [
{
label: '最外层1',
resourcesId: '1',
children: [
{
label: '第二层1',
resourcesId: '1-1',
children: [
{
label: '第三层1',
resourcesId: '1-1-1',
children: [
{
label: '第四层1',
resourcesId: '1-1-1-1'
},{
label: '第四层2',
resourcesId: '1-1-1-2'
}
]
},{
label: '第三层2',
resourcesId: '1-1-2'
},{
label: '第三层3',
resourcesId: '1-1-3'
}
]
},{
label: '第二层2',
resourcesId: '1-2'
}
]
}
]
6.运行结果:
以 resourcesId 为 ‘1-1’ label 为 ‘第二层1’ 的为例
let a = getAllChildrenNodes(list, '1-1') //子节点
let b = getAllParentNodes(list, '1-1') //父节点
let c = getBrotherNodes(list, '1-1') //兄弟节点
console.log(a);
console.log(b);
console.log(c);