当前位置: 首页 > news >正文

较为完善的搜索函数

一.搜索函数的使用

在当代web制作中,多条件搜索不论是在后台系统或者说移动端都极为常见,其中最常见的莫过于在后台系统中的多条件搜索,根据后台庞杂的数据,我们往往需要一个好用的搜索函数来帮助我们进行多条件搜索

1.当执行多条件搜索的时候,我使用的是filter封装的函数,封装函数的代码可以提升我们代码的可读性以及可复用性,同时封装的越好,使用起来越简便,以下是我封装的一个利用filter封装的多条件搜索函数,同时也注意了对空值的处理
 

function multiConditionSearch(data, conditions) {
  // 根据sessionStorage中的change_id来选择不同的数据源
 
    data = globalData;
  // 取消所有复选框的选中状态
  $(".notice_nav .checkbox_id input").prop("checked", false);

  // 辅助函数,用于获取嵌套对象的值
  function getNestedValue(obj, path) {
    const parts = path.split(".");
    return parts.reduce((current, key) => {
      return current && current[key] !== undefined ? current[key] : null;
    }, obj);
  }

  // 过滤掉无效的条件
  const validConditions = Object.fromEntries(
    Object.entries(conditions).filter(([_, value]) => {
      if (typeof value === "object" && !Array.isArray(value)) {
        if ("like" in value) {
          return value.like.trim() !== "";
        } else if ("start" in value && "end" in value) {
          return value.start.trim() !== "" || value.end.trim() !== "";
        }
      }
      return (
        value !== null && value !== undefined && String(value).trim() 
!== ""
      );
    })
  );

  // 根据有效条件过滤数据
  const searchResult = data.filter((item) => {
    return Object.keys(validConditions).every((key) => {
      const condition = validConditions[key];
      // 获取嵌套属性的值
      const itemValue = getNestedValue(item, key);

      if (typeof condition === "object" && !Array.isArray(condition)) {
        if (condition.start && condition.end) {
          const itemTime = new Date(itemValue).getTime();
          const startTime = new Date(condition.start).getTime();
          const endTime = new Date(condition.end).getTime();
          return itemTime >= startTime && itemTime <= endTime;
        } else if (condition.like) {
          if (typeof itemValue === "string") {
            return itemValue
              .toLowerCase()
              .includes(condition.like.toLowerCase());
          }
          return false;
        }
      } else {
        return itemValue === condition;
      }
    });
  });

  // 调用 render 函数进行数据渲染
  page = 0;
  
    render(searchResult);
  return searchResult;}

2.该函数可以放在公共界面,在其他页面调用

conditions = {
      name: { like: $("#drug_name").val() },

      create_time: { start: $("#start_date").val(), end: $("#end_date").val() },
    };
    data = multiConditionSearch(data, conditions);

3.在页面上调用仅仅需要设置不同的类名用以匹配对应的数据即可,后续的赋值则是确保分页在点击的时候可以获取到正确的数据,而不是错误的全局数据,同时我的函数也可以处理嵌套的数据,关键函数即

// 辅助函数,用于获取嵌套对象的值
  function getNestedValue(obj, path) {
    const parts = path.split(".");
    return parts.reduce((current, key) => {
      return current && current[key] !== undefined ? current[key] : null;
    }, obj);
  }

4.用于提取嵌套的数据格式,类似于

const obj = {
  a: {
    b: {
      c: "Hello, World!"
    }
  }
};

// 使用 getNestedValue 获取值
const result1 = getNestedValue(obj, "a.b.c");
console.log(result1);  // 输出: "Hello, World!"

// 路径无效的示例
const result2 = getNestedValue(obj, "a.x.y");
console.log(result2);  // 输出: null

// 路径部分为 null 或 undefined 的示例
const result3 = getNestedValue(obj, "a.b.c.d");
console.log(result3);  // 输出: null

总结

通过这个函数,我可以处理目前我遇到的各种多条件搜索,且并不影响太多性能的同时,可以随时通过增加筛选条件来适配更多的条件筛选

相关文章:

  • LangChain 动态任务分发:开启大模型任务流的巅峰之术(三)
  • CRMEB标准版/开源版商城系统【遇坑解决】
  • 3.5 二分查找专题:LeetCode 852. 山脉数组的峰值
  • 单片机自学总结
  • 如何搭建一个安全经济适用的TRS交易平台?
  • Linkreate wordpressAI插件 24小时自动生成原创图文,新增从百度、必应搜索引擎自动获取相关下拉关键词
  • SpringBoot第三站(4):配置嵌入式服务器使用外置的Servlet容器
  • LeetCode56☞合并区间
  • 超参数优化算法:scikit-opt库、Scikit-Optimize库
  • GPU视频编解码:X86 VideoProcessFrame 视频编解码入门(二)
  • Git提交前时间检查
  • Golang | 每日一练 (6)
  • Mysql 安装指南(小白入门)
  • 基于FPGA轨道交通6U机箱CPCI脉冲板板卡
  • vs2017版本与arcgis10.1的ArcObject SDK for .NET兼容配置终结解决方案
  • 【笔记】计算机网络——数据链路层
  • 10.PE导出表
  • 3.8 Spring Boot监控:Actuator+Prometheus+Grafana可视化
  • 【vue2 + Cesium】使用Cesium、添加第三方地图、去掉商标、Cesium基础配置、地图放大缩小事件、获取可视区域、层级、高度
  • Python第六章01:列表(lsit)定义语法
  • 西班牙葡萄牙突发全国大停电,欧洲近年来最严重停电事故何以酿成
  • 杭州6宗涉宅用地收金125.76亿元,萧山区地块楼面价冲破5万元/平米
  • 马上评|“AI神医宇宙”欺诈,连演员都不请了
  • 暴涨96%!一季度“中国游中国购”持续升温,还有更多利好
  • 持续更新丨伊朗官员:港口爆炸事件已致5人死亡
  • 韩国检方重启调查金建希操纵股价案