Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
¿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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!