Reputation: 139
I have an Array for recipes and inside of it I have another Array ingredients with some objects, what I want is to filter the recipes array by comparing the nested object key ingredient with entered value in the Input field (keyup event is working and I have the values form the input fild stored in a variable called enteredValue )...
Soo can you help me find how to filter recipes using those nested array
const recipes = [{
"id": 1,
"name": "Limonade de Coco",
"servings": 1,
"ingredients": [{
"ingredient": "Lait de coco",
"quantity": 400,
"unit": "ml"
},
{
"ingredient": "Jus de citron",
"quantity": 2
}
],
"time": 10,
"description": "Mettre les glaçons à votre goût dans le blender, ajouter le lait, la crème de coco, le jus de 2 citrons et le sucre. Mixer jusqu'à avoir la consistence désirée",
"appliance": "Blender",
"ustensils": ["cuillère à Soupe", "verres", "presse citron"]
},
{
"id": 2,
"name": "Poisson Cru à la tahitienne",
"servings": 2,
"ingredients": [{
"ingredient": "Thon Rouge (ou blanc)",
"quantity": 200,
"unit": "grammes"
},
{
"ingredient": "Concombre",
"quantity": 1
},
{
"ingredient": "Tomate",
"quantity": 2
},
{
"ingredient": "Lait de Coco",
"quantity": 100,
"unit": "ml"
}
],
"time": 60,
"description": "Découper le thon en dés, mettre dans un plat et recouvrir de jus de citron vert (mieux vaut prendre un plat large et peu profond). Laisser reposer au réfrigérateur au moins 2 heures. (Si possible faites-le le soir pour le lendemain. Après avoir laissé mariner le poisson, coupez le concombre en fines rondelles sans la peau et les tomates en prenant soin de retirer les pépins. Rayer la carotte. Ajouter les légumes au poissons avec le citron cette fois ci dans un Saladier. Ajouter le lait de coco. Pour ajouter un peu plus de saveur vous pouver ajouter 1 à 2 cuillères à soupe de Crème de coco",
"appliance": "Saladier",
"ustensils": ["presse citron"]
}
]
let filteredRecettesIngrediants = recipes.map(receipt => {
return receipt.ingredients.filter(ingredientKey => {
return (ingredientKey.ingredient === 'Carotte')
})
})
console.log(filteredRecettesIngrediants)
Upvotes: 1
Views: 3121
Reputation:
recipes.filter(recipe => recipe.ingredients.some(ingred => ingred.ingredient == inputValue))
The some
method returns true if at least one entry satisfies the function given, in this case that the value of "ingredient"
in each ingredient in the recipe has a value of inputValue
. If at least one entry returns true then the recipe contains that ingredient so you can add the whole recipe to the filtered output list.
Upvotes: 1
Reputation: 781
If you want to get every recipe which contains the entered ingredient, try this:
recipes.filter(r => r.ingredients.some(i => i.ingredient === enteredValue));
This gets all items in recipes
where at least one item in ingredients
has a value for ingredient
that is equal to enteredValue
.
Upvotes: 2