let dt = [{
id: '2',
children: [{
id: '2-1',
children: [{
id: '2-1-1',
children: [{
id: '2-1-1-1',
children: []
}]
}]
},
{
id: '2-2',
children: [{
id: '2-2-1',
children: [{
id: '2-2-1-1',
children: []
}]
}]
}
]
}]
//查找所有上级方法
function treeFindPath (tree, func, path = []) {
if (!tree) return []
for (const data of tree) {
// 这里按照你的需求来存放最后返回的内容吧
path.push(data.id)
if (func(data)) return path
if (data.children) {
const findChildren = treeFindPath(data.children, func, path)
if (findChildren.length) return findChildren
}
path.pop()
}
return []
}
//调用
console.log(treeFindPath(dt, data=> data.id=='2-1-1-1')) //["2", "2-1", "2-1-1", "2-1-1-1"]
console.log(treeFindPath(dt, data=> data.id=='2-2-1-1')) //["2", "2-2", "2-2-1", "2-2-1-1"]
树形结构根据指定节点id,查询所有上级
于 2023-03-15 17:26:46 首次发布