js递归的应用场景

42 阅读1分钟

1、js根据值递归筛选树结构

//搜索框
<a-input-search style="margin-bottom: 8px" placeholder="Search" @change="onChange" />
//树组件
<a-tree
      :checkable="checkable"
      :treeData="filterTreeData"
      :checkedKeys.sync="checkedKeys"
      @check="onCheck"
    >
traverseTree(tree, value) {
      let newarr = []
      //遍历树
      tree.forEach((node) => {
      //包含所传值,则新数组push整个节点
        if (node.name.indexOf(value) > -1) { 
          newarr.push(node)
        } else {
        //判断是否有子节点,有则递归
          if (node.children&& node.children.length > 0) {
            let child = this.traverseTree(node.children, value)
            //若子节点递归后newarr不为空,则将其父节点一起保存
            if (child && child.length > 0) {
              let obj = {
                ...node,
                children: child,
              }
              newarr.push(obj)
            }
          }
        }
      })
      return newarr
    },
    
    onChange(e) {
      const value = e.target.value //搜索值
      this.filterTreeData = this.traverseTree(this.treeData, value)
    },
 

2、递归删除

    deleteNode(tree) {
      return tree.filter((node) => {
        if (node.menuType === 3) { //删除条件
          return false
        }
        if (node.children) {
          node.children = this.deleteNode(node.children)
        }
        return true
      })
    },

3、递归设置节点属性(selectable)

//判断只能选叶子节点
  recursiveNode(tree) {
    tree.forEach((item)=>{ //遍历树
      if(!item.children || item.children.length == 0){
        item.selectable = true
      }
      //如果有子节点,则selectable设置为不可选
      if(item.children && item.children.length >0){ 
        item.selectable = false
        this.recursiveNode(item.children)
      }
    })
    return tree
  },

4、递归匹配id,返回这个节点数据

findNodeById(tree, id) {
      for (var i = 0; i < tree.length; i++) {
        var node = tree[i]
        if (node.id === id) {
          return node
        }
        if (node.children && node.children.length > 0) {
          var foundNode = this.findNodeById(node.children, id)
          if (foundNode) {
            return foundNode
          }
        }
      }
      return null
    },

5、递归与数组匹配,返回新数组

findNodeByArr(tree, arr, newarr = []) {
      tree.map((node) => { //遍历树
      //若数组包含此节点id,则新数组保存此节点相关信息
        if (arr.includes(node.id)) {
          newarr.push({ 
            id: node.id,
            name: node.name,
          })
        }
        if (node.childList && node.childList.length > 0) {
          this.findNodeByArr(node.childList, arr, newarr)
        }
      })
      return newarr
    },