Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
¿Cómo filtrar una matriz una matriz mientras se verifica el valor de una entrada?

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

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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 ); }
about 4 years ago · Juan Pablo Isaza Denunciar

0

  • Dado que 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) }) }
about 4 years ago · Juan Pablo Isaza Denunciar

0

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 }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda