'Only want one item to be returned in get route

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!`);
});


Solution 1:[1]

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;

};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Varun Mehta