Aejg
Aejg

Reputation: 81

Check if each object in array of objects contains a value that is in another array (JavaScript)

If I have the following array of objects:

    const movies = [
        {
            movieTitle: "The House That Jack Built",
            movieGenre: "Thriller",
            movieDirector: "Lars Von Trier",
            movieStarring: "Matt Dillon, Uma Therman",
        },
        {
            movieTitle: "Mother!",
            movieGenre: "Thriller",
            movieDirector: "Darren Aronofsky",
            movieStarring: "Jennifer Lawrence",
        },
        {
            movieTitle: "Hot Fuzz",
            movieGenre: "Comedy",
            movieDirector: "Edgar Wright",
            movieStarring: "Simon Pegg",
        }
    ]

and the following array:

const filters = ["Jennifer Lawrence", "Comedy"]

How can I create a new array containing only the objects that have a value that's in the filters array (in this case the last 2)?

Thanks!

Upvotes: 1

Views: 40

Answers (1)

blex
blex

Reputation: 25634

Using filter, some and Object.values:

const movies  = [{movieTitle:"The House That Jack Built",movieGenre:"Thriller",movieDirector:"Lars Von Trier",movieStarring:"Matt Dillon, Uma Therman"},{movieTitle:"Mother!",movieGenre:"Thriller",movieDirector:"Darren Aronofsky",movieStarring:"Jennifer Lawrence"},{movieTitle:"Hot Fuzz",movieGenre:"Comedy",movieDirector:"Edgar Wright",movieStarring:"Simon Pegg"}];
const filters = ["Jennifer Lawrence", "Comedy"];

const res = movies.filter(
  movie => Object.values(movie).some(v => filters.includes(v))
);

console.log(res);

Upvotes: 2

Related Questions