我正在嘗試使用現有物件中的值創建一系列新物件以推送到我的資料庫。
這是現有物件:
{
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和正確measure和quantity(如上面的物件所寫)。
這是我到達的地方:
//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.
uj5u.com熱心網友回復:
問題似乎是函式“getIngredients”只回傳 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
})
由于您尚未發布“getIngredients”方法,因此很難確切說明如何調整它以回傳名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488749.html
標籤:javascript 数组 目的
上一篇:收集JSON物件中的所有路徑
