// 思路:
// 1. 封装一个函数,先遍历第一层数据,先看是否有满足条件的元素,如果有将这条数据记录下来,结束遍历,返回这条数据
// 2. 如果没有满足条件的元素,看当前数据中有没有children,且children数组是否为空,如果为空则结束遍历返回false。
// 3. 如果children数组不为空,则递归执行该函数
const treeData = [
{
id:'wuguo',
name: '吴国'
},
{
id:'shuguo',
name:'蜀国',
children: [
{
id:'liubei',
name:'刘备'
},
{
id:'jiangjun',
name:'将军',
children:[
{
id:'guanyu',
name:'关羽'
},
{
id:'zhangfei',
name:'张飞'
}
]
},
{
id:'junshi',
name:'军师',
children:[
{
id:'zhugeliang',
name:'诸葛亮',
children: [
{
id:'qizi',
name:'黄月英'
}
]
}
]
}
]
}
]
const hasChild = (ele) => ele && ele.children && ele.children.length > 0;
const depthFind = (tree, cb) => {
if(!Array.isArray(tree)) throw new Error('必须是数组')
let res = null
for(let i=0;i<tree.length;i++){
if(cb(tree[i])){
res = tree[i]
break;
}else if(hasChild(tree[i])){
const childRes = depthFind(tree[i].children, cb)
if(childRes){
res = childRes
break;
}
}
}
return res
}
// 在数据中找出id为qizi的数据
const result = depthFind(treeData, (node) => {
return node.id == 'qizi'
})
console.log(result); // { id: 'qizi', name: '黄月英' }
如何从树形结构数据中找出满足条件的数据
于 2024-01-11 17:24:03 首次发布