請原諒我,因為我仍然了解 JSON 和路由。我的任務是按配方名稱回傳一些物件,并包含其成分串列以及用“numSteps”鍵值對替換指令的物件:count_of_instruction_steps。我很難洗掉結果的“說明”鍵。這是我問過的另一個問題的延續。
食譜的 JSON 資料:
{
"recipes": [
{
"name": "scrambledEggs",
"ingredients": [
"1 tsp oil",
"2 eggs",
"salt"
],
"instructions": [
"Beat eggs with salt",
"Heat oil in pan",
"Add eggs to pan when hot",
"Gather eggs into curds, remove when cooked",
"Salt to taste and enjoy"
]
},
{
"name": "garlicPasta",
"ingredients": [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
"instructions": [
"Heat garlic in olive oil",
"Boil water in pot",
"Add pasta to boiling water",
"Remove pasta from water and mix with garlic olive oil",
"Salt to taste and enjoy"
]
},
{
"name": "chai",
"ingredients": [
"400mL water",
"100mL milk",
"5g chai masala",
"2 tea bags or 20 g loose tea leaves"
],
"instructions": [
"Heat water until 80 C",
"Add milk, heat until 80 C",
"Add tea leaves/tea bags, chai masala; mix and steep for 3-4 minutes",
"Remove mixture from heat; strain and enjoy"
]
}
]
}
任務:回傳的 GET 請求http://localhost:3000/recipes/details/garlicPasta:如果配方存在:
Response body (JSON):
{
"details":
{
"ingredients": [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
"numSteps":5
}
}
Status: 200
如果配方不存在:
Response body (JSON): {}
Status: 200
我實際得到的:
{
name: "garlicPasta",
ingredients: [
"500mL water",
"100g spaghetti",
"25mL olive oil",
"4 cloves garlic",
"Salt"
],
instructions: {
numSteps: 5
}
}
我的代碼:
app.get('/recipes/details/:name', (req, res) => {
let count = 0
const numSteps = {}
const recipe = recipes.find(r => r.name === req.params.name)
const instructions = recipes.map(r => {
if(r.name === req.params.name){
for(let instruction of r.instructions){
count = 1
}
}
})
recipe.instructions = {"numSteps": count}
res.status(200).send(recipe);
})
uj5u.com熱心網友回復:
我不會嘗試回傳修改后的“配方”物件,因為您需要的回應形狀不同。您可以使用現有代碼找到正確的配方,然后只需創建一個具有所需回應屬性的新物件。請注意,您可以只使用 recipe.instructions.length 來了解有多少步驟。
app.get('/recipes/details/:name', (req, res) => {
let count = 0;
const recipe = recipes.find(r => r.name === req.params.name);
const output = {
details: {
ingredients: recipe.ingredients,
numSteps: recipe.instructions.length
}
};
res.status(200).send(output);
})
uj5u.com熱心網友回復:
您不是在創建details屬性,而是instructions在結果中添加了您不想要的屬性。
無需回圈計數numSteps,您只需使用r.instructions.length. 并且一旦找到帶有 的食譜recipes.find(),就不需要另一個回圈來查找食譜名稱。
您沒有檢查是否可以找到配方,因此您{}在這種情況下回傳。
app.get('/recipes/details/:name', (req, res) => {
const recipe = recipes.find(r => r.name === req.params.name);
let result = {};
if (recipe) {
result.details = {
ingredients: recipe.ingredients,
numSteps: recipe.instructions.length
};
}
res.status(200).send(recipe);
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/418643.html
標籤:
