How to return an object with a given value?

I’m doing a search filter. I need to return the entire object containing the given actor by the user. I can find the actor, but I’m not sure how to return the object where the actor is.

JSON file:

{
    "title": "American Assassin",
    "year": 2017,
    "cast": [
        "Dylan O'Brien",
        "Michael Keaton",
        "Sanaa Lathan",
        "Shiva Negar",
        "Taylor Kitsch"
    ],
    "genres": []
},
{
    "title": "Mother!",
    "year": 2017,
    "cast": [
        "Jennifer Lawrence",
        "Javier Bardem",
        "Michelle Pfeiffer",
        "Domhnall Gleeson",
        "Ed Harris",
        "Kristen Wiig"
    ],
    "genres": []
}

My filter function:

checkCast(allMovies) {
      return filter(allMovies, (movie) => {
        const actor = filter(movie.cast, (actor) => {
          return actor.toLowerCase().includes(this.search.cast.toLowerCase())
        })
        console.log(actor)
        return actor
      });
    }

Hope everything is clear.

>Solution :

You need to filter the allMovies array by looking for an actor in the case array. Use Array.some() (or lodash _.some()) to return true if a matching actor is found.

const search = { cast: 'bardem' };

function checkCast(allMovies) {
  return allMovies.filter(movie =>
    movie.cast.some(actor =>
      actor.toLowerCase().includes(search.cast.toLowerCase())
    )
  );
}

const allMovies = [{"title":"American Assassin","year":2017,"cast":["Dylan O'Brien","Michael Keaton","Sanaa Lathan","Shiva Negar","Taylor Kitsch"],"genres":[]},{"title":"Mother!","year":2017,"cast":["Jennifer Lawrence","Javier Bardem","Michelle Pfeiffer","Domhnall Gleeson","Ed Harris","Kristen Wiig"],"genres":[]}]

const result = checkCast(allMovies)

console.log(result)

Leave a Reply