You need to enable JavaScript to run this app. Vue.js中如何使用Lodash等JS库从分类对象检索匹配商品名
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何使用Lodash等JS库从分类对象检索匹配商品名

原Lodash写法失效的核心原因
  • 匹配逻辑和需求完全不匹配:_.some 传入普通对象作为谓词时,会对集合内的元素做严格属性全等判断,也就是要求商品的product_name必须和传入的"Shir"完全一致才会被判定为匹配,像"Shirt 123"这类名称里包含"Shir"的条目根本不会被识别,自然无法返回正确结果。
  • 功能定位偏差:原代码使用_.find仅会返回「第一个内部存在匹配商品的分类对象」,没有提取跨分类下所有符合检索条件的商品,无法实现商品检索的实际目标。
具体实现方案

基于Lodash的实现

可以根据实际的页面展示需求,选择两种检索结果形式:

  1. 扁平提取全部分类下的匹配商品,形成独立的商品列表
// 替换searchKeyword为实际的页面检索输入值
const searchKeyword = "Shir";
const matchedProducts = _.flatMap(this.allCategories, 'product')
  .filter(product => 
    _.includes(_.toLower(product.product_name), _.toLower(searchKeyword))
  );
  1. 保留原有分类层级结构,仅过滤出每个分类下匹配关键词的商品
const searchKeyword = "Shir";
const filteredCategories = this.allCategories
  .filter(category => 
    _.some(category.product, p => 
      _.includes(_.toLower(p.product_name), _.toLower(searchKeyword))
    )
  )
  .map(category => ({
    ...category,
    // 仅保留分类下符合检索条件的商品
    product: _.filter(category.product, p => 
      _.includes(_.toLower(p.product_name), _.toLower(searchKeyword))
    )
  }));

如果要修正你最初写的_.flow逻辑,只需要把严格匹配的对象谓词替换为模糊判断的函数即可:

_.find(this.allCategories, _.flow(
  _.property('product'),
  _.partialRight(_.some, productItem => 
    _.includes(_.toLower(productItem.product_name), 'shir')
  )
));

原生JS实现(无额外依赖)

现代浏览器、Vue 2/Vue 3 默认构建配置下均可直接运行:

const searchKeyword = "Shir";
// 扁平提取所有分类下的匹配商品
const matchedProducts = this.allCategories
  .flatMap(category => category.product ?? [])
  .filter(product => 
    product.product_name?.toLowerCase().includes(searchKeyword.toLowerCase())
  );

// 保留分类结构的过滤版本
const filteredCategories = this.allCategories
  .map(category => ({
    ...category,
    product: (category.product ?? []).filter(product => 
      product.product_name?.toLowerCase().includes(searchKeyword.toLowerCase())
    )
  }))
  .filter(category => category.product.length > 0);
实用注意点
  • 匹配前统一对字符串做大小写转换,可以避免因大小写差异导致的漏匹配,提升检索容错性
  • 基础的关键词包含匹配足以应对绝大多数商品列表检索场景,如果需要支持拼音检索、错字容错、分词匹配这类更复杂的能力,可以引入Fuse.js这类专门的模糊检索库
  • 对分类下的product字段做非空兜底判断,可以避免接口返回数据结构异常导致的页面报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.12.01 06:06:03