Vue.js中如何使用Lodash等JS库从分类对象检索匹配商品名
原Lodash写法失效的核心原因
- 匹配逻辑和需求完全不匹配:
_.some传入普通对象作为谓词时,会对集合内的元素做严格属性全等判断,也就是要求商品的product_name必须和传入的"Shir"完全一致才会被判定为匹配,像"Shirt 123"这类名称里包含"Shir"的条目根本不会被识别,自然无法返回正确结果。 - 功能定位偏差:原代码使用
_.find仅会返回「第一个内部存在匹配商品的分类对象」,没有提取跨分类下所有符合检索条件的商品,无法实现商品检索的实际目标。
具体实现方案
基于Lodash的实现
可以根据实际的页面展示需求,选择两种检索结果形式:
- 扁平提取全部分类下的匹配商品,形成独立的商品列表
// 替换searchKeyword为实际的页面检索输入值 const searchKeyword = "Shir"; const matchedProducts = _.flatMap(this.allCategories, 'product') .filter(product => _.includes(_.toLower(product.product_name), _.toLower(searchKeyword)) );
- 保留原有分类层级结构,仅过滤出每个分类下匹配关键词的商品
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
相关产品推荐
相关产品推荐

