Skip to content
On this page

表格过滤方法

一个过滤表格数据的方法,它接受三个参数 :表格数据、搜索条件和匹配规则。该方法会根据搜索条件和匹配规则过滤表格数据,并返回过滤后的数据。

javascript
function filterTableData(data, searchData, matchRules) {
  // 如果搜索条件为空或无效,返回原数据
  if (!searchData || typeof searchData !== 'object' || Object.keys(searchData).length === 0) {
    return data;
  }

  // 默认匹配规则
  const defaultRules = {
    fuzzy: (itemValue, condition) =>
      String(itemValue).toLowerCase().includes(String(condition).toLowerCase()),
    exact: (itemValue, condition) =>
      String(itemValue) === String(condition),
    range: (itemValue, condition) => {
      if (!Array.isArray(condition) return false;
      const [start, end] = condition;
      return itemValue >= start && itemValue <= end;
    }
  };

  return data.filter(item => {
    // 遍历所有搜索条件
    return Object.entries(searchData).every(([key, condition]) => {
      // 如果条件为空则跳过该条件
      if (condition === null || condition === undefined || condition === '') {
        return true;
      }

      const itemValue = item[key];

      // 获取该字段的匹配规则
      const ruleType = matchRules?.[key] || 'fuzzy'; // 默认为模糊匹配

      // 应用匹配规则
      switch (ruleType) {
        case 'fuzzy': // 模糊匹配(不区分大小写)
          return defaultRules.fuzzy(itemValue, condition);

        case 'exact': // 全等匹配(区分大小写)
          return defaultRules.exact(itemValue, condition);

        case 'range': // 范围匹配
          return defaultRules.range(itemValue, condition);

        default: // 未知规则使用模糊匹配
          console.warn(`Unknown match rule "${ruleType}" for field "${key}", using fuzzy match`);
          return defaultRules.fuzzy(itemValue, condition);
      }
    });
  });
}

使用示例:

javascript
// 示例数据
const tableData = [
  { id: 1, name: '小明', code: '123456', updateTime: 1750854335834 },
  { id: 2, name: '小红', code: '123456', updateTime: 1750854340000 },
  { id: 3, name: '小明明', code: '345678', updateTime: 1750854355226 },
  { id: 4, name: '小李', code: '123', updateTime: 1750854360000 },
]

// 搜索条件
const searchData = {
  name: '', // 模糊匹配
  code: '123456', // 全等匹配
  updateTime: [1750854335834, 1750854355226], // 时间范围
}

// 匹配规则配置
const matchRules = {
  name: 'fuzzy', // 模糊匹配
  code: 'exact', // 全等匹配
  updateTime: 'range', // 范围匹配
}

// 执行过滤
const filteredData = filterTableData(tableData, searchData, matchRules)
console.log(filteredData)
/* 输出:
[
  { id: 1, name: '小明', code: '123456', updateTime: 1750854335834 }
]
*/

功能说明:

  1. 灵活的匹配规则配置

    • fuzzy:模糊匹配(不区分大小写),适用于文本字段
    • exact:全等匹配(区分大小写),适用于编码、ID 等精确字段
    • range:范围匹配,适用于时间戳、数值范围
  2. 默认匹配规则

    • 未指定匹配规则的字段默认使用模糊匹配
    • 遇到未知规则类型时使用模糊匹配并输出警告
  3. 智能空值处理

    • 条件值为 nullundefined 或空字符串时自动跳过
    • 确保空条件不会影响过滤结果
  4. 类型安全处理

    • 模糊匹配和全等匹配自动转换为字符串比较
    • 范围匹配确保数值比较,非数组条件返回 false

使用场景示例:

场景 1:混合匹配模式

javascript
const searchData = {
  productName: '手机', // 模糊匹配
  sku: 'P-12345', // 全等匹配
  price: [100, 500], // 范围匹配
}

const matchRules = {
  productName: 'fuzzy',
  sku: 'exact',
  price: 'range',
}

场景 2:部分字段使用默认规则

javascript
const searchData = {
  username: 'john', // 使用默认模糊匹配
  email: 'example@domain.com', // 全等匹配
  lastLogin: [startTimestamp, endTimestamp], // 范围匹配
}

const matchRules = {
  email: 'exact',
  lastLogin: 'range',
}
// username 未指定规则,使用默认模糊匹配

场景 3:处理特殊数据类型

javascript
const searchData = {
  isActive: true, // 布尔值全等匹配
  tags: 'urgent', // 数组内模糊匹配
  createdAt: [start, end], // 日期范围
}

const matchRules = {
  isActive: 'exact',
  tags: 'fuzzy',
  createdAt: 'range',
}

// 在数据项中:
// { isActive: true, tags: ['urgent', 'important'], createdAt: 1672531200000 }

注意事项:

  1. 范围匹配

    • 只接受长度为 2 的数组 [start, end]
    • 确保传入的时间戳/数值有效
    • 包含边界值(≥start 且 ≤end)
  2. 大小写敏感

    • 模糊匹配不区分大小写
    • 全等匹配区分大小写("ABC" ≠ "abc")
  3. 空值处理

    • 当字段值为 undefinednull 时:
      • 模糊匹配:空字符串包含任何文本?返回 false
      • 全等匹配:严格比较
      • 范围匹配:数值比较(NaN 返回 false)
  4. 性能建议

    • 对于大型数据集,考虑添加索引或分页
    • 范围匹配在数值字段上效率较高
    • 文本模糊匹配可能成为性能瓶颈

此方法提供了灵活的字段匹配规则配置,可以根据不同字段的特性使用最适合的匹配方式,同时保持代码的简洁性和可维护性。

上次更新于: