I am using Node and Express to practice writing routes and was given the following exercise. Can anyone help with the response to my GET request? Given the follow JSON data:
{
"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"
]
}
]
}
I am supposed to make a GET request and return the following:
{
"recipeNames":
[
"scrambledEggs",
"garlicPasta",
"chai"
]
}
This is what I have so far:
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)
})
which is giving me:
{
[
"scrambledEggs",
"garlicPasta",
"chai"
]
}
How do I get it in a JSON object with key "recipeNames" and value the array?
app.get('/recipes', (req, res) => {
const recipes = data.recipes;
const recipeNames = recipes.recipeNames.map(r => r.name)
res.status(200).send({recipeNames})
})
You can make it as bellow:
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)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.