获取子节点的所有祖父节点-ts
interface IItemObj{
label: string,
value: number,
children?: IItemObj[]
}
type GetNodes = (treeOptions: IItemObj[], treeIds: number[]) => number[][]
let treeOptions: IItemObj[] = [
{
label: '我的',
value: 1,
children: [
{
label: '我的信息',
value: 2,
children: [
{
label: '我的基础信息',
value: 3
},
{
label: '我的信息积分信息',
value: 10,
children: [
{
label: '我的基础信息',
value: 11,
children: [
{
label: '我的基础信息',
value: 12
},
]
},
]
}
]
},
{
label: '我的邀请',
value: 4
}
]
},
{
label: '首页',
value: 5,
children: [
{
label: '首页列表',
value: 6
},
{
label: '首页目录',
value: 7
}
]
}
]
let getNodes: GetNodes = (treeOptions, treeIds) => {
const fn = (children: IItemObj[], id: number): number[] => {
for(let op of children){
if(op.value === id) return ([op.value])
if(op?.children){
let ids = fn(op.children, id)
if(ids) return ([op.value, ...ids])
}
}
}
return treeIds.map(id => fn(treeOptions, id) || [])
}
console.log(getNodes(treeOptions, [11, 5, 3]))