递归查找所有的父元素节点
// 查找所有父元素
export function getAllParentNode(treeData: any, id: string, parentKey: string): [] {
const temp = [] as any
// 递归函数
const forFn = function (data: any, id: string, parentKey: string): void {
// 遍历树
for (let i = 0; i < data.length; i++) {
const item = data[i]
if (item.id === id) {
// 查找到指定节点加入集合
temp.push(item)
// 查找其父节点
forFn(treeData, item[parentKey], parentKey)
// 不必向下遍历,跳出循环
break
} else {
if (item.children) {
// 向下查找到id
forFn(item.children, id, parentKey)
}
}
}
}
forFn(treeData, id, parentKey)
return temp
}
递归查找所有父元素的id
export function familyTreeIds(
treeData: any,
ids: any[],
parentKey: string
): string[] {
const ret = [] as string[]
ids.forEach((id: string) => {
const ids = getAllParentNode(treeData, id, parentKey).map((v: any) => v.id)
ids.forEach((v: any) => {
if (!ret.includes(v)) {
ret.push(v)
}
})
})
return ret
}