You need to enable JavaScript to run this app. 如何基于UI动态生成的过滤对象筛选JavaScript数组
优惠活动
大模型
产品
解决方案
定价
更多

如何基于UI动态生成的过滤对象筛选JavaScript数组

动态多条件数组数据筛选实现

需求说明

基于UI端动态生成的过滤对象,对结构化业务数组做模糊匹配筛选,核心规则为:

  • 匹配不区分大小写,忽略用户输入的前后空格
  • 字段值包含输入关键词即判定为命中
  • 支持过滤对象动态增减字段,无需硬编码匹配逻辑

输入参考定义

// UI动态生成的过滤条件
const filter = {
  city: 'pana',
  hospname: 'sara'
};

// 待筛选的原始数据
const data = [
  {
    "city": "Hot Springs",
    "hospname": "St. Vincent Hot Springs",
    "version": "VA48A",
    "sysid1": "CT67400",
    "type": "CompressedFile",
    "rowIndex": 0,
    "selected": false,
    "disabled": true
  },
  {
    "city": "Panama City",
    "hospname": "Bay Medical Center",
    "version": "VA48A",
    "sysid1": "CT67399",
    "type": "CompressedFile",
    "rowIndex": 1,
    "selected": false,
    "disabled": true
  },
  {
    "city": "Sarasota",
    "hospname": "Sarasota Memorial Hospital",
    "version": "VA44A",
    "sysid1": "C7393",
    "type": "CompressedFile",
    "rowIndex": 2,
    "selected": false,
    "disabled": true
  },
  {
    "city": "DAVENPORT",
    "hospname": "Genesis Medical Center",
    "version": "VA48A",
    "sysid1": "C6333",
    "type": "CompressedFile",
    "rowIndex": 6,
    "selected": false,
    "disabled": true
  }
];

实现代码

结合给出的预期输出验证,当前筛选逻辑为条目命中任意一个过滤条件即保留;如果需要调整为所有条件同时满足的与逻辑,只需将代码中的some替换为every即可。

function filterTableData(dataList, filterCondition) {
  // 预处理过滤规则,统一格式避免类型异常
  const filterRules = Object.entries(filterCondition).map(([field, keyword]) => ({
    field,
    keyword: String(keyword ?? '').trim().toLowerCase()
  })).filter(rule => rule.keyword); // 自动过滤空关键词的无效规则

  return dataList.filter(item => {
    // 只要命中任意一条有效规则就保留条目
    return filterRules.some(rule => {
      const targetValue = String(item[rule.field] ?? '').toLowerCase();
      return targetValue.includes(rule.keyword);
    });
  });
}

// 执行筛选
const filteredResult = filterTableData(data, filter);

输出结果说明

执行代码后得到的结果和预期完全一致:

  • 命中city: 'pana'规则的条目:Panama City 对应条目(字段小写为panama city,包含关键词pana)
  • 命中hospname: 'sara'规则的条目:Sarasota Memorial Hospital 对应条目(字段小写为sarasota memorial hospital,包含关键词sara)
  • 剩余2条数据无任何规则命中,被过滤排除

注:预期输出中Sarasota对应条目的sysid1字段值存在笔误,原始数据中该字段值为C7393,匹配逻辑不会修改字段的原始值。

内容的提问来源于stack exchange,提问作者Nishanth。

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 06:54:08