数据结构
let treeData = [{
id: 1,
label: '一级 1',
children: [{
id: 4,
label: '二级 1-1',
children: [{
id: 9,
label: '三级 1-1-1'
}, {
id: 10,
label: '三级 1-1-2'
}]
}]
}, {
id: 2,
label: '一级 2',
children: [{
id: 5,
label: '二级 2-1'
}, {
id: 6,
label: '二级 2-2'
}]
}, {
id: 3,
label: '一级 3',
children: [{
id: 7,
label: '二级 3-1'
}, {
id: 8,
label: '二级 3-2'
}]
}];
const findNodeInTree = (data, key, callback) => {
for (let i = 0; i < data.length; i++) {
if (data[i].label == key) {
return callback(data[i], i, data)
}
if (data[i].children) {
findNodeInTree (data[i].children, key, callback)
}
}
}
// 所查找到的节点要存储的方法
let ObjResult={}
findNodeInTree(treeData, "二级 1-1", (item, index, arr) => {
ObjResult== item
})
// 此时就是ObjResult=对应的要查找的节点
console.log(ObjResult)
第二个例子
let res = [{
name:"一级-1",
children:[{
name:"二级-1",
children:[{
name:"三级-1-1",
children:[{
name:"四级-1-1-1"
}]
},{
name:"三级-1-2",
children:[{
name:"四级-1-2-1"
}]
}]
},{
name:"二级-2",
children:[{
name:"三级-2-1",
children:[{
name:"四级-2-1-1"
}]
},{
name:"三级-2-2",
children:[{
name:"四级-2-2-1"
}]
}]
}]
}]
function treeFindPath(tree,func,path=[]){
if(!tree) return[]
for(let data of tree){
path.push(data.name)
console.log(path)
if(func(data)){
return path
}
if(data.children){
const findChildren = treeFindPath(data.children,func,path)
console.log(findChildren,"children")
if(findChildren.length) return findChildren
}
path.pop()
// console.log(path)
}
return []
}
let result = treeFindPath(res,data=>data.name=='四级-2-2-1')
console.log(result)
此例子的另一种方式
let testResult
function treeFindPath(tree,func,path=[]){
if(!tree) return[]
for(let data of tree){
path.push(data.name)
console.log(path)
if(func(data)){
let path1 = JSON.stringify(path || [])
testResult = JSON.parse(path1)
// return path
}
if(data.children){
const findChildren = treeFindPath(data.children,func,path)
// console.log(findChildren,"children")
// if(findChildren.length) return findChildren
}
path.pop()
}
}
let result = treeFindPath(res,data=>data.name=='四级-2-2-1')
console.log(testResult)