簡體   English   中英

如何在 Javascript 中從 Array of Array 中過濾項目

[英]How to filter items from Array of Array in Javascript

如何根據數組中的流派項過濾電影標題?

const result= [
    {
      "title": "Mad Max: Fury Road",
      "genre": [
        "Action",
        "Adventure",
        "Sci-Fi"
      ]
    },
    {
      "title": "The Hunger Games: Mockingjay Part 1",
      "genre": [
        "Adventure",
        "Thriller"
      ]
    },
    {
      "title": "Jurassic World",
      "genre": [
        "Action",
        "Adventure",
        "Sci-Fi"
      ]
    },
    {
      "title": "Everest",
      "genre": [
        "Drama",
        "Thriller"
      ]
    },
    {
      "title": "Insurgent",
      "genre": [
        "Adventure"
      ]
    },
    {
      "title": "Sicario",
      "genre": [
        "Action",
        "Crime",
        "Drama"
      ]
    }
  ];

假設如果我想根據流派過濾電影標題名稱,例如:“科幻”,那么它應該返回電影標題數組,例如:[“瘋狂麥克斯:狂暴之路”、“侏羅紀世界”]

嘗試了地圖和過濾器的各種組合但不起作用

const newResult = result.map((curr) => curr.genre.filter((ele) => ele === search)).filter((ele) => ele);

我們使用filter返回所有通過某些條件的電影。

對於filter的通過條件,我們在提供的流派數組上使用every

如果在某個條件下調用它的數組 ( genreList ) 中的所有元素every返回 true,則 each 返回 true。

對於every的條件,我們檢查電影的流派數組是否包含給定genreList數組中的條目。

所以在英語中,這段代碼說“請給我所有具有genreList中給出的所有類型的電影”。

 const result= [ { "title": "Mad Max: Fury Road", "genre": [ "Action", "Adventure", "Sci-Fi" ] }, { "title": "The Hunger Games: Mockingjay Part 1", "genre": [ "Adventure", "Thriller" ] }, { "title": "Jurassic World", "genre": [ "Action", "Adventure", "Sci-Fi" ] }, { "title": "Everest", "genre": [ "Drama", "Thriller" ] }, { "title": "Insurgent", "genre": [ "Adventure" ] }, { "title": "Sicario", "genre": [ "Action", "Crime", "Drama" ] } ]; const moviesByGenres = (moviesList, genreList) => { return moviesList.filter((m) => { return genreList.every((g) => m.genre.includes(g)); }); } // All action movies console.log(moviesByGenres(result, ["Action"])); // All action+adventure movies console.log(moviesByGenres(result, ["Action", "Adventure"]));

使用Array#filter選擇符合設定條件的相關項目,並使用Array#map選擇您感興趣的所選項目的屬性。

 const result= [ { "title": "Mad Max: Fury Road", "genre": [ "Action", "Adventure", "Sci-Fi" ] }, { "title": "The Hunger Games: Mockingjay Part 1", "genre": [ "Adventure", "Thriller" ] }, { "title": "Jurassic World", "genre": [ "Action", "Adventure", "Sci-Fi" ] }, { "title": "Everest", "genre": [ "Drama", "Thriller" ] }, { "title": "Insurgent", "genre": [ "Adventure" ] }, { "title": "Sicario", "genre": [ "Action", "Crime", "Drama" ] } ], search = "Sci-Fi"; newResult = result //which items meet the set criteria? .filter(({genre}) => genre.includes(search)) //what about those items am I zeroing in on? .map(({title}) => title); console.log( newResult );

經過反復試驗找到了答案

const n = result.filter((curr) => curr['genre'].includes("Action"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM