Jop
Jop

Reputation: 135

How can I return a list of objects based on their values

I have a local server that I am using for practice and to learn. In it, I have an array of objects:

let movies = [
//1
{
    title: 'Lord of the Rings',
    actor: 'Orlando',
    genre: 'adventure',
    director: 'person'

} ,
//2
{
    title: 'Harry Potter',
    actor: 'Daniel Radcliffe',
    genre: 'Fantasy',
    director: 'person',
    movie_id: "7"
} ,
//3
{
    title: 'The Prestige',
    actor: 'Christian Bale',
    genre: 'adventure',
    director: 'person'
} , 
//4
{
    title: 'The Dark Knight',
    actor: 'Christian Bale',
    genre: 'adventure',
    director: 'person'
} , 
//5
{
    title: 'Pirates of the Caribbean',
    actor: 'Orlando',
    genre: 'adventure',
    director: 'person'  
    }
]

in which I am able to return a specific object based on the inputted URL value:

ex. http://localhost:8081/movies?actor=Orlando

will return the first object containing object key/value "actor: 'Orlando'"

while using this code:

app.get("/movies", (req, res) => {
if (req.query.title) {
    res.json(movies.find((movie) => {
        return movie.title === req.query.title
    }));
}
if (req.query.actor) {
    res.json(movies.find((movie) => {
        return movie.actor === req.query.actor
    }));
}
    if (req.query.director) {
        res.json(movies.find((movie) => {
            return movie.director === req.query.director
        }));
    }
    res.json(movies);
});

However, this only returns the first object it encounters with the requested value. What do I need to add/change to have it return all movies by the same actor/direct/genre etc?

The ideal return when I type the aforementioned URL should be:

{
    title: 'Lord of the Rings',
    actor: 'Orlando',
    genre: 'adventure',
    director: 'person'

}
{
    title: 'Pirates of the Caribbean',
    actor: 'Orlando',
    genre: 'adventure',
    director: 'person'  
    }

thanks for all and any help!

Upvotes: 1

Views: 822

Answers (1)

Erwin Schens
Erwin Schens

Reputation: 444

The problem is, that you want to return an array of json objects. By using the find method you will only receive a the first found element. Try using the filter function.

Example:

if (req.query.actor) {
    res.json(movies.filter((movie) => {
        return movie.actor === req.query.actor
    }));
}

Result for http://localhost:8081/movies?actor=Orlando:

[{
    title: 'Lord of the Rings',
    actor: 'Orlando',
    genre: 'adventure',
    director: 'person'

}
{
    title: 'Pirates of the Caribbean',
    actor: 'Orlando',
    genre: 'adventure',
    director: 'person'  
}]

Upvotes: 2

Related Questions