遍历-找到匹配的节点

案例1:树结构treeData,找到与this.activeData.id匹配的节点

this.nodeClickData=this.getNodeClickData(this.treeData)

getNodeClickData(val){
  for(const item of val){
    if(item.id==this.activeData.id){
      console.log('匹配的节点==',item)
      return item  //找到之后,就返回
    }
    // 如果没有找到,就看看this.treeData有没有子级
    let childResult=null
    if(item.childrenKey && item.childrenKey.length>0){
      childResult=this.getNodeClickData(item.childrenKey)
    }
    if(childResult){
       return childResult  //子级找到结果,就返回
    }
  }
  return null
}

案例2: 找到选中节点的父级节点

// this.nodeClickData---选中的数据
const expandedKeys=this.getParentkeys(this.nodeClickData,this.treeData)

/*
* targetNode---选中节点
* treeData  --- 树全部数据
*/
getParentkeys(targetNode,treeData,parentKeys=[]){
 for(cosnt node of treeData){
   if(node.id==targetNode.id){
      return [...parentKeys,node.id]
   }
   // 没找到,如果有子级,就遍历子级
   if(node.childrenKey && node.childrenKey.length>0){
     const keys=this.getParentkeys(targetNode,node.childrenKey,[...parentKeys,node.id])
     if(keys){
       return keys
     }
   }
 }
 return null
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值