我正在处理大型产品数据集,我需要根据用户的输入值过滤产品列表。我的产品数据集如下所示:
const products = [
{id: 0, name: "Product1", brand: "Theraflu", itemCode: "THE110", price: 5.45},
{id: 1, name: "Product2", brand: "Benadryl", itemCode: "BEN121", price: 7.05},
{id: 2, name: "Product3", brand: "Listerine", itemCode: "LIS204", price: 4.55},
{id: 3, name: "Product4", brand: "Tylenol", itemCode: "TYL116", price: 6.10},
];
我能够根据每个单独的产品对象中可用的不同字段过滤产品列表,如下所示:
const keys = ["name", "brand", "itemCode"];
const getFilteredProducts = (filterText) => {
const newProducts = products.filter(product => keys.some(key => product[key].toLowerCase().includes(filterText.toLowerCase())));
return newProducts;
}
console.log(getFilteredProducts("Tylenol"));
当我根据单个字段过滤产品时,此代码实际上有效。但是,当我尝试组合不同的字段时,例如:
console.log(getFilteredProducts("product4 Tylenol"));
this 的返回值是一个空数组。有没有办法在不改变现有过滤功能的情况下实现这一点?
似乎您需要自己搜索每个单词filterText
。也许是这样的:
const keys = ["name", "brand", "itemCode"];
const getFilteredProducts = (filterText) => {
const filterWords = filterText.split(" ");
const newProducts = [];
for (const word of filterWords) {
newProducts.push(
products.filter(product => keys.some(key =>
product[key].toLowerCase().includes(word.toLowerCase())
))
);
}
return [].concat(...newProducts).filter((value, index, self) =>
self.findIndex((m) => m.id === value.id) === index
);
}
console.log(getFilteredProducts("Tylenol Product3"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句