Tengo un problema al tratar de filtrar mi matriz (ver más abajo), estoy tratando de filtrar mis recetas mientras verifico si un ingrediente está dentro de una receta.
Encontrarás un ejemplo minimalista de mi problema a continuación. Primero el JSON
{"recipes": [ { "id": 1, "name" : "Limonade de Coco", "servings" : 1, "ingredients": [ { "ingredient" : "Lait de coco", "quantity" : 400, "unit" : "ml" }, { "ingredient" : "Jus de citron", "quantity" : 2 }, { "ingredient" : "Crème de coco", "quantity" : 2, "unit" : "cuillères à soupe" }, { "ingredient" : "Sucre", "quantity" : 30, "unit" : "grammes" }, { "ingredient": "Glaçons" } ] }] } <input class="input" /> <script> const input = document.querySelector(".input") async function getRecipes() { const response = await (await fetch("./recipes.json")).json(); const recipes = response.recipes; return ({ recipes: [...recipes] }); }; function filter(recipes) { input.addEventListener("input", () => { var filteredRecipes = recipes.filter(recipe => { return recipe.ingredients.ingredient.toLowerCase().includes(input.value.toLowerCase()) }) console.log(filteredRecipes) }) } async function init() { const { recipes } = await getRecipes(); filter(recipes) } init() </script>Este error está llegando a la consola:
index.html:23 TypeError no capturado: no se pueden leer las propiedades de undefined (leyendo 'toLowerCase')
lo cual está completamente bien ya que cada ingrediente no es un ingrediente. Probé un forEach en la matriz de ingredientes pero no pude obtener el resultado.
Entonces, FilteredRecipes debería regresar aquí, o mi receta, o una matriz vacía.
Gracias por adelantado
Esto probablemente se deba a "await" delante de fetch en la función init. Pruébalo así;
async function init() { const { recipes } = getRecipes().then(res => filter(res.recipes)) .catch(err => //catch any error ); }recipe.ingredients es una matriz, debe usar .filter() o su equivalente para verificar si un ingrediente incluye el texto buscado. Cambie su función de filter a algo como esto
function filter(recipes) { input.addEventListener("input", () => { var filteredRecipes = recipes.filter(recipe => { return recipe.ingredients.filter(({ingredient}) => ingredient.toLowerCase().includes(input.value.toLowerCase())).length > 0 }) console.log(filteredRecipes) }) }Está vinculando un detector de eventos en la entrada cada vez que filtra.
Solo necesita configurarlo una vez al inicio.
También para proporcionar una alternativa más detallada:
function filter_recipes(recipes, value) { let ans = [] let filter = value.toLowerCase() for (let recipe of recipes) { for (let item of recipe.ingredients) { if (item.ingredient.toLowerCase().includes(filter)) { ans.push(recipe) } } } return ans }