javascript - 如何使用多个条件过滤 JavaScript 对象

标签 javascript arrays json

我有一个包含食谱的 JSON 文件。 现在我的主页上有一个搜索栏,用户可以在其中选中和取消选中复选框以选择他想要搜索的食谱属性(名称、成分、标签、类别)。他还可以选中多个条件。

现在我想根据选定的条件过滤我的对象。 我知道是否有例如只检查了“name”我可以去

recipes.filter(e -> e.name.indexOf(searchString) >= 0)

但是我怎么能动态地说“如果还检查了成分,则在名称或成分中筛选找到的结果”。

希望你明白。谢谢。

最佳答案

您可以将所有属性放在一个数组中,然后使用 .some() 检查是否有任何属性匹配。

const recipes = [
  { name: "pizza", ingredients: "dough tomato mince", category: "meal" },
  { name: "pie", ingredients: "dough sugar", category: "dessert" },
  { name: "stew", ingredients: "potato mince onoin", category: "meal" },
  { name: "donut", ingredients: "sugar", category: "dessert" }
];
// Get these from the checkboxes:
const selected_attributes = [
  "name",
  "ingredients"
];
// Get this from the searchbar:
const seachbar_query = "do";
// Filter all recipes where the name or ingredients contains "do".
// We expect "pizza" and "pie', which contain dough in their ingredients.
// And we also expect "donuts", whose name starts with "do"
const filtered = recipes.filter( recipe => {
  return selected_attributes.some( attribute => {
    return recipe[ attribute ].includes( seachbar_query );
  });
});

console.log( filtered );

关于javascript - 如何使用多个条件过滤 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56473605/

相关文章:

javascript - WebView2:通过 Javascript 代码在 C# 中设置对象属性

c# - 加快 C# 中的查询生成器(字符串连接)

jquery - Json:使用 JQuery 解析以 HTML 形式显示

asp.net - 如何循环遍历JSON数据?

javascript - jQuery .find() 多种类型的输入

javascript - 使用基本的 javascript xml 访问 RSS feed 中的 'media:thumbnail' 标签

arrays - Julia:不同类型的数组

javascript - jQuery 数组处理不当 : length= 0 bug?

javascript - Webpack - 如何通过 image-webpack-loader 将 jpg/png 转换为 webp

JavaScript 匹配数组