// 通过子节点ID查找所有关联的父节点
getTreeIds(tree, nodeId, config){
const { children = 'children', id = 'id' } = config || {};
const toFlatArray = (tree, parentId) => {
return tree.reduce((t, _) => {
const child = _[children]
return [
...t,
parentId ? { ..._, parentId } : _,
...(child && child.length ? toFlatArray(child, _[id]) : [])]
}, [])
};
const getIds = flatArray => {
let ids = [nodeId]
let child = flatArray.find(_ => _[id] === nodeId)
while (child && child.parentId) {
ids = [child.parentId, ...ids]
child = flatArray.find(_ => _[id] === child.parentId)
}
return ids
}
return getIds(toFlatArray(tree))
}
// 数据
data(){
return {
treeData: [
{
id: 1,
label: 'test1',
children: [
{
id: 2,
label: 'test1-1',
children: [
{
id: 3,
label: 'test1-1-1'
},
{
id: 4,
label: 'test1-1-2',
children: [
{
id: 5,
label: 'test1-1-1-1'
}
]
}
]
}
]
}
]
}
}
// 调用
let arr = this.getTreeIds(this.treeData, 5); // arr的值为[1, 2, 4, 5]
Vue里定义方法:通过子节点ID查找所有关联的父节点ID
最新推荐文章于 2023-12-22 20:07:19 发布