简体   繁体   中英

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!

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM