我有一个包含食谱的 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/