如何从树形结构数据中找出满足条件的数据

// 思路:
// 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: '黄月英' }
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值