js获取树形结构的所有节点(以下调用方法的写法是用在vue项目中)

1、先看数据结构

2、实现代码

  //获取树形结构的所有节点
lookForAllId(data = [], arr = []) {
      for (let item of data) {
        arr.push(item);
        if (item.children && item.children.length)
          this.lookForAllId(item.children, arr);
      }
      return arr;
},

3、调用

let arrAll = this.lookForAllId(this.treedata);  //this.treedata为树形结构的数据
        arrAll.forEach((item2) => {
          console.log(item2)  //所有的节点
          //判断是否还有子级 
          if (item2.children == null) {
          //没有子级
          }else{
          //有子级
        });

看打印结果

 

 完结!

posted @ 2021-10-27 10:19  相戀  阅读(1612)  评论(0)    收藏  举报