zoukankan      html  css  js  c++  java
  • JS实现树形结构数据的模糊搜索查询

    简单示例:

    需求:输入 “题2” 字,希望树形结构中带有 “题2” 字的项显示,即使父节点没有,但子节点含有,父节点仍要返回。

    let arr = [
      {
        title: '标题1',
        children: [
          {
            title: '标题11',
            children: null
          },
          {
            title: '标题21',
            children: null
          }
        ]
      },
      {
        title: '标题2',
        children: [
          {
            title: '标题22',
            children: null
          }
        ]
      },
      {
        title: '标题3',
        children: null
      }
    ];

    代码实现:

    let mapTree = (value, arr) => {
      let newarr = [];
      arr.forEach(element => {
        if (element.title.indexOf(value) > -1) { // 判断条件
          newarr.push(element);
        } else {
          if (element.children && element.children.length > 0) {
            let redata = mapTree(value, element.children);
            if (redata && redata.length > 0) {
              let obj = {
                ...element,
                children: redata
              };
              newarr.push(obj);
            }
          }
        }
      });
      return newarr;
    };
    
    console.log(mapTree('题2', arr));

    结果:

    [
      {
        title: '标题1',
        children: [
          {
            title: '标题21',
            children: null
          }
        ]
      },
      {
        title: '标题2',
        children: [
          {
            title: '标题22',
            children: null
          }
        ]
      }
    ]

    复杂示例:

    如果需要匹配多个属性,代码实现如下:

    matchTreeData(arr, searchCon) {
      let newArr = [];
      let searchNameList = ['name', 'code', 'title'];
      arr.forEach((item) => {
        for (let i = 0, len = searchNameList.length; i < len; i++) {
          let nameKey = searchNameList[i];
          if (item.hasOwnProperty(nameKey)) {
            if (item[nameKey] && item[nameKey].indexOf(searchCon) !== -1) {
              newArr.push(item);
              break;
            } else {
              if (item.childList && item.childList.length > 0) {
                let resultArr = this.matchTreeData(item.childList, searchCon);
                if (resultArr && resultArr.length > 0) {
                  newArr.push({
                    ...item,
                    childList: resultArr
                  })
                  break;
                }
              }
            }
          } else {
            continue;
          }
        }
      })
      return newArr;
    }
  • 相关阅读:
    jquery 序列化form表单
    nginx for windows 安装
    nodejs idea 创建项目 (一)
    spring 配置 shiro rememberMe
    idea 2018 解决 双击shift 弹出 search everywhere 搜索框的方法
    redis 在windows 集群
    spring IOC控制反转和DI依赖注入
    redis 的安装
    shiro 通过jdbc连接数据库
    handlebars的用法
  • 原文地址:https://www.cnblogs.com/moqiutao/p/15259981.html
Copyright © 2011-2022 走看看