Im trying to make a get route that will only return the names of recipes but im getting all the info in the array instead. Is there some thing im missing?
const express = require('express');
const { recipes } = require('./data/data.json');
const app = express();
function filterByQuery(query, recipesArray) {
let filterResults = recipesArray;
if (query.name) {
filterResults = filterResults.filter(recipes => recipes.name === query.name);
}
return filterResults;
};
app.get('/recipes', (req, res) => {
let results = recipes;
if (req.query) {
results = filterByQuery(req.query, results);
}
res.json(results);
});
app.listen(3000, () => {
console.log(`Server is running on port 3000!`);
});
CodePudding user response:
My goal is the have the just the names of the recipes returned in a new array.
First off, it appears from your other code that the recipes
variable is an array of recipe objects which has properties such as .name
. If so, you would get all the names of all the recipes by doing this:
app.get('/recipes', (req, res) => {
const names = recipes.map(recipe => recipe.name);
res.json(names);
});
It's unclear why you were trying to call filterByQuery()
because it is programmed to return whole recipes that match a specific name. That's a completely different function than getting just the names of all the recipes.
In addition, to get all recipes, you don't need to use req.query
as there is no query parameter involved in getting all recipes.
CodePudding user response:
You are basically doing filtering of records
function filterByQuery(query, recipesArray) {
let filterResults = recipesArray;
if (query.name) {
filterResults = filterResults.filter(recipes => recipes.name === query.name);
}
return filterResults;
};
Here recipes are object not string values, so it is returning the objects which have recipes.name equal to query.name.
function filterByQuery(query, recipesArray) {
let results;
if (query.name) {
results = recipesArray.filter(recipes => recipes.name === query.name);
}
return results?.length ? results[0].name : null;
};