尝试循环访问对象的值并插入到新对象 (JS) 中



我正在尝试使用现有对象的值创建一系列新对象,以推送到我的数据库。

下面是现有对象:

{
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' }
]
}

基本上,我有一个函数,插入并返回配方的id到一个表中,然后插入并返回/或找到相关成分的id,最后一部分(我正在努力)是将返回的recipe_id,ingredient_id和正确的measurequantity(如上面对象中所写)结合起来。

这里是我得到的:

//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
})
}

期望的输出将是:

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.

问题似乎是函数" getingredient "只返回id。一旦获取了它们,就无法知道哪个ID对应哪个成分。改变这种情况的一种方法是使该方法返回一个包含ID和成分名称的数组。然后你可以像这样匹配它们:

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
})

既然你还没有发布"getingredient "函数,很难确切地说如何调整它以返回名称。

相关内容

  • 没有找到相关文章

最新更新