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;
    }
  • 相关阅读:
    Spring如何处理线程并发问题?
    什么是spring?
    如何通过sql语句完成分页?
    哪一个List实现了最快插入?
    请说出作用域public,private,protected,以及不写时的区别?
    使用什么命令查看用过的命令列表?
    静态变量和实例变量的区别?
    使用什么命令查看磁盘使用空间? 空闲空间呢?
    什么是 Mybatis?
    是否可以继承String类?
  • 原文地址:https://www.cnblogs.com/moqiutao/p/15259981.html
Copyright © 2011-2022 走看看