Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading