我有一个这样的数组:
const state = {
products: [
{ name: "Potato", amount: "3"},
{ name: "Butter", amount: "1000" },
{ name: "Salt", amount: "2000" },
//{name: "Egg", amount: "10"},
{ name: "Tomato", amount: "5"},
{ name: "Sour Milk", amount: "5"}
],
recipes: [
{
name: "Mashed potatoes",
ingredients: [
{ name: "Potato", amount: "5"},
{ name: "Butter", amount: "30"},
{ name: "Salt", amount: "15"}
],
instructions: "Some Text"
},
{
name: "Tomato Omelette",
ingredients: [
{ name: "Tomato", amount: "1" },
{ name: "Egg", amount: "1" },
{ name: "Salt", amount: "10" },
{ name: "Butter", amount: "40" }
],
instructions: "Some text"
}
]
};
我想按我可以用我的产品烹饪的食谱过滤我的食谱数组(在这种情况下,我不能做“番茄煎蛋卷”,因为我没有鸡蛋,也不能做“土豆泥”,因为我没有没有足够的土豆)。
到目前为止,我尝试了不同的方法,但我没有想出一个完整的解决方案。
我最接近的解决方案是:
const filterRecipes = (filter, products, recipes) => {
if(filter === 'available products') {
//Getting all product names for future tests
const productsNames = products.map(item => item.name);
//Here we will filter all our recipes by available products
const result = recipes.filter(recipe => {
//Getting all ingredient names of the current recipe
const ingredientNames = recipe.ingredients.map(item => item.name);
//If we have all products for our recipe
//we will add it to our filtered array
if (ingredientNames.every((name) => productsNames.includes(name))){
return true;
}
})
console.log(result);
}
};
这仅适用于产品名称,但不适用于其数量。当我试图检查它刚刚打破的金额时。
呼如林
潇湘沐
跃然一笑
慕桂英4014372
随时随地看视频慕课网APP
相关分类