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

171
Vistas
Intentando iterar a través de los valores de un objeto e insertarlo en un nuevo objeto (JS)

Estoy tratando de crear una serie de nuevos objetos usando los valores de un objeto existente para enviarlos a mi base de datos.

Aquí está el objeto existente:

 { name: 'Pasta', method: 'Cook pasta', ingredients: [ { measure: 'tbsp', quantity: '1', ingredient_name: 'lemon' }, { measure: 'g', quantity: '1', ingredient_name: 'salt' }, { measure: 'packet', quantity: '1', ingredient_name: 'spaghetti' }, { measure: 'litre', quantity: '1', ingredient_name: 'water' } ] }

Básicamente, tengo una función que inserta y devuelve la identificación de la receta en una tabla, luego inserta y devuelve/o encuentra las identificaciones de los ingredientes relevantes y la parte final (con la que estoy luchando) es combinar la recipe_id devuelta, el ingredient_id y la measure y quantity correctas (como está escrito en el objeto de arriba).

Aquí es donde he llegado:

 //starting point is here async function addNewRecipe(newRecipe, db = connection) { console.log(newRecipe) const recipeDetails = { recipe_name: newRecipe.name, recipe_method: newRecipe.method, } const ingredientsArray = newRecipe.ingredients const [{ id: recipeId }] = await db('recipes') .insert(recipeDetails) .returning('id') const ingredientsWithIds = await getIngredients(ingredientsArray) //returns an array of ids ingredientsWithIds.forEach((ingredientId) => { let ingredientRecipeObj = { recipe_id: recipeId, //works ingredient_id: ingredientId, //works measure: newRecipe.ingredients.measure, //not working - not sure how to match it with the relevant property in the newRecipe object above. quantity: newRecipe.ingredients.quantity,//not working - not sure how to match it with the relevant property in the newRecipe object above. } //this is where the db insertion will occur }) }

La salida deseada sería:

 ingredientRecipeObj = { recipe_id: 1 ingredient_id: 1 measure: tbsp quantity: 1 } then insert this into db followed by: ingredientRecipeObj = { recipe_id: 1 ingredient_id: 2 measure: g quantity: 1 } then insert into db etc. etc.
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

El problema parece ser que la función "getIngredients" devuelve solo los ID. Una vez que los haya obtenido, no tiene forma de saber qué ID es para qué ingrediente. Una forma de cambiar eso es hacer que el método devuelva una matriz tanto del ID como del nombre del ingrediente. Entonces podrías emparejarlos así:

 const ingredientsWithIds = await getIngredients(ingredientsArray) //now an array of objects with ingredient_name and id ingredientsWithIds.forEach((ingredient) => { const recipeIngredient = ingredientsArray.find(ri => ri.ingredient_name === ingredient.ingredient_name) const ingredientRecipeObj = { recipe_id: recipeId, ingredient_id: ingredient.id, measure: recipeIngredient.measure, quantity: recipeIngredient.quantity, } //this is where the db insertion will occur })

Como no ha publicado la función "getIngredients", es difícil decir exactamente cómo adaptarla para que también devuelva el nombre.

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