簡體   English   中英

從 GET 請求返回 JSON object

[英]return a JSON object from a GET request

我正在使用 Node 和 Express 來練習編寫路線,並獲得了以下練習。 任何人都可以幫助回復我的 GET 請求嗎? 給定以下 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 請求並返回以下內容:

{
    "recipeNames":
        [
            "scrambledEggs",
            "garlicPasta",
            "chai"
        ]
}

這是我到目前為止所擁有的:

app.get('/recipes', (req, res) => {
  const recipes = data.recipes;
  const recipeNames = {}
  const arr = []
  for(let i = 0; i < recipes.length; i++){
    let recipe = recipes[i]
    let recipeName = recipe.name
 arr.push(recipeName)
      //recipeNames[arr] = [recipeName]

 }

  res.status(200).send(arr)
})

這給了我:

{
  [
     "scrambledEggs",
     "garlicPasta",
     "chai"
  ]
}

如何使用鍵“recipeNames”在 JSON object 中獲取它並為數組賦值?

app.get('/recipes', (req, res) => {
  const recipes = data.recipes;
  const recipeNames = recipes.recipeNames.map(r => r.name)

  res.status(200).send({recipeNames})
})

你可以把它做成如下:

app.get('/recipes', (req, res) => {
    const recipes = data.recipes;
    const recipeNames = {}
    const arr = []

    for(let i = 0; i < recipes.length; i++){
        let recipe = recipes[i]
        let recipeName = recipe.name
        arr.push(recipeName)
        //recipeNames[arr] = [recipeName]

    }

    let forSend = {"recipeNames": arr}

    res.status(200).send(forSend)
})       

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM