如何修复TobaccoModel实例数据过滤时的精准匹配问题?
精准过滤TobaccoModel实例的flavorTypeCategory
问题背景
现有TobaccoModel实例数组,需要根据用户选择的类型数组type过滤数据,但当前过滤逻辑会把包含目标类型子串的条目也返回(比如选"fruity"时,"fruity-spice"的条目也会被选中),需要实现完全匹配的过滤效果。
现有代码
数据数组
const BrandFlavorData = [ new TobaccoModel(264, "dleaf", "Example", "Banana", "fruity", "Example description #1", "low"), new TobaccoModel(265, "dleaf", "Example #2", "Berry", "berry-ice", "Example description #2", "low"), new TobaccoModel(266, "dleaf", "Example #3", "Cola", "fruity-spice", "Example description #3", "low") ]
原过滤函数
const exampleFunction = () => { let filteredData = BrandFlavorData.filter((item) => { let meetsTypeCriteria = type.some(element => item.flavorTypeCategory.includes(element) && !item.flavorTypeCategory.includes(type.join('-'))) return meetsTypeCriteria }) }
状态定义
const [type, setType] = React.useState([]);
TobaccoModel类
class TobaccoModel { constructor(id, category, brandName, flavor, flavorTypeCategory, description, nicotine) { this.id = id, this.category = category, this.brandName = brandName, this.flavor = flavor, this.flavorTypeCategory = flavorTypeCategory, this.description = description this.nicotine = nicotine } } export default TobaccoModel;
解决方案
原逻辑的问题在于使用item.flavorTypeCategory.includes(element)进行子串匹配,导致包含目标类型的长字符串也被误判。需要改为完全相等匹配,同时兼容多选场景:
修复后的过滤函数
const exampleFunction = () => { // 无选中类型时返回全部数据 if (type.length === 0) return [...BrandFlavorData]; // 精准匹配:仅保留flavorTypeCategory完全等于选中类型之一的条目 return BrandFlavorData.filter(item => type.includes(item.flavorTypeCategory)); }
逻辑说明
- 当用户没有选择任何类型(
type为空数组),直接返回全部数据,避免过滤空结果。 - 使用
type.includes(item.flavorTypeCategory)替代子串匹配,确保只有条目分类完全等于用户选中的某一个类型时才会被保留。 - 天然支持多选:如果用户选择多个类型(比如
["fruity", "berry-ice"]),会返回所有分类匹配其中任意一个的条目。
内容的提问来源于stack exchange,提问作者Tony Chronic
相关产品推荐
相关产品推荐

