通过父级id 递归找到所有子类

选中的元素

 数据结构大概:

data: [ {id:123321321, name: '哇哈哈' }, {id:123321321, name: '哇哈哈' , childrenList: [{id:888888, name: '起飞' }]}]

思路:

1、是否能在第一层找到选中的id,如果找到了,就开始递归该对象,直到找到最底层的子类

2、如果没有在第一层找到选中的id,开始递归该对象,直到找到匹配选中id的对象,而后执行第一步,找到最底层的子类

实现代码:

/*
* 第一步
* selectList  树选择控件选中的元素
*/

let categoryList = []

const findSonByRecursion = (selectList) => { // 递归树查找最底层的类目
    selectList.forEach((item) => {
      treeDataSource.forEach((tree) => {
        if (item.value === tree.id) {
          // 第一层就找到了
          hasChildrenList(tree); // 开始下渗查找最底层的类目
        } else {
          // 否则递归继续下渗查找
          if (tree.childrenList) {
            findChildrenList(tree.childrenList, item.value);
          }
        }
      });
    });
  };

/*
* 第二步
*/

const hasChildrenList = (tree) => { // 已经匹配上id的对象,找到该对象的最底层
    if (tree.childrenList) {
      tree.childrenList.forEach((item) => {
        if (item.childrenList) {
          hasChildrenList(item);
        } else {
          categoryList.push(item);
        }
      });
    } else {
      categoryList.push(tree);
    }
  };

/*
* 第三步
*/

const findChildrenList = (dataList, value) => {
    dataList.forEach((item) => {
      // childrenList 第一层就找到了
      if (item.id === value) {
        if (item.childrenList) {
          hasChildrenList(item); // 查找是否还有子集
        } else {
          categoryList.push(item);
        }
      } else if (item.childrenList) {
        // 否则继续下渗查找
        findChildrenList(item.childrenList, value);
      }
    });
  };



 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值