You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Lodash在Angular应用对象数组多字段中实现模糊搜索

基于Lodash实现Angular多字段模糊搜索

你需要的“任意目标字段命中即保留”的IN式OR匹配逻辑,完全可以通过Lodash的原生方法实现,不需要手写复杂的遍历判断。

现有代码改造方案

  • 提前确认项目中已经按需引入Lodash的对应工具方法
  • 将原始全量产品数组存在组件属性中,作为搜索的固定数据源
  • 修改原有mySearch()方法的内部逻辑,实现双字段模糊匹配

直接给出适配后可运行的代码:

// 按需引入需要的Lodash方法
import { filter, some, toLower, includes, isEmpty, trim } from 'lodash';

// 组件类内属性定义
allProducts = [
  { "_id": "1", "productName": "test name 1", "article": "11111" },
  { "_id": "2", "productName": "test name 2", "article": "11111" },
  { "_id": "3", "productName": "test name 3", "article": "4" },
  { "_id": "4", "productName": "test name 4", "article": "11111" },
  { "_id": "5", "productName": "test name 5", "article": "111111" },
  { "_id": "6", "productName": "test name 6", "article": "11111111" },
  { "_id": "7", "productName": "test name 7", "article": "4d" }
];

// 存储筛选结果,绑定到页面渲染
filteredProducts = [...this.allProducts];

mySearch() {
  // 获取搜索框输入内容,去除首尾空格后统一转小写
  const keyword = trim(toLower(this.searchForm.get('search')?.value || ''));

  // 关键词为空时,重置展示全量数据
  if (isEmpty(keyword)) {
    this.filteredProducts = [...this.allProducts];
    return;
  }

  // 核心筛选逻辑
  this.filteredProducts = filter(this.allProducts, (item) => {
    // 任意一个目标字段命中关键词,即保留该条目
    return some([item.productName, item.article], (fieldValue) => {
      return includes(toLower(String(fieldValue)), keyword);
    });
  });
}

逻辑对齐说明

这套实现完全匹配你的需求:

  • 匹配逻辑是OR关系:只要productName或article任意一个字段的内容包含输入的关键词,就会被筛选出来,等价于SQL中的productName LIKE '%xx%' OR article LIKE '%xx%'的IN式判断
  • 做了全场景兼容:
    • 关键词和字段值统一转小写匹配,不受输入大小写影响
    • 字段值统一转成字符串再匹配,避免后续遇到数字类型字段时出现类型报错
    • 搜索框输入全空格时自动重置筛选状态,展示全量数据

输入关键词「4」时的筛选结果和你给出的预期完全一致:

  1. _id=3 的条目:article字段值为「4」,直接命中
  2. _id=4 的条目:productName字段值为「test name 4」,包含关键词,命中
  3. _id=7 的条目:article字段值为「4d」,包含关键词,命中
    其余无4字段值的条目会被自动过滤,不会出现误匹配。

可选优化

如果不想依赖keydown事件触发搜索,可以在组件初始化阶段直接监听搜索控件的valueChanges事件自动触发筛选,减少不必要的事件绑定,逻辑和上述方法完全一致。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 19:06:02