将多个对象字段与JS中的输入值匹配

哈米德·吉莫

我正在处理大型产品数据集,我需要根据用户的输入值过滤产品列表。我的产品数据集如下所示:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Js:将值注入多个输入字段

如何动态获取匹配的输入字段以将值添加到JavaScript中的对象?

将多个 url 从多个值插入到输入字段中

将输入值匹配到数组中的JSON对象

使用pattern属性匹配输入字段中的多个特定值之一

将多个选中的复选框的值传递到多个对应的输入字段中

在输入字段中显示选定的对象值

如何在Vue.js的输入值字段中输入对象数组?

匹配对象数组中多个字段匹配的文档

AngularJS:在输入文本字段中显示多个对象的属性值,以逗号分隔

在多个选择字段中的输入字段中显示值

如何将动态输入值绑定到 Vue.js 中的 v-for 输入字段

将数组值与嵌套while循环内的输入字段匹配

如何使用php将多个输入文本字段值添加到db中

Elasticsearch查询将多个值匹配到单个字段

如何通过单击反应js中的按钮将输入字段中的值设置为空?

如何将多个值从表单输入推入mongoose.model中的对象数组?

如何在多个输入字段中填充以下对象?

将文本字段中的输入与数组元素进行匹配

合并JS中的两个对象,然后根据单个输入选择多个值

如何使用 jQuery oninput 函数将多个输入字段的值显示到单个输入字段

匹配同一字段中的多个值

将字段值与猪袋中的值匹配

React Js-无法在输入字段中输入值

将每个键具有多个值的对象转换为 JS 中的对象数组

如何在输入字段中添加多个值

如何在IONIC 3中将多个输入字段作为JSON对象发布到服务器

更改多个对象上相同字段的值-JS

使用值是返回表单JS的输入字段中的值