簡體   English   中英

使用按值嵌套的 arrays 過濾對象數組

[英]Filter array of objects with arrays nested by value

我正在嘗試從大量對象中過濾掉結果。 基本上我有一個輸入,我想在輸入匹配一個或部分關鍵字時過濾結果。


export default [
    {
       "id":1014,
       "item":19021,
       "name":"name 1",
       "description":"",
       "image":"http://images.jpg",
       "keywords":[
          "Cake",
          "Party",
          "Birthday"
       ],
    },
    {
       "id":1015,
       "item":19023,
       "name":"name 22",
       "description":"",
       "image":"http://images.jpg",
       "keywords":[
          "NHL",
          "Party"
       ],
    },
    {
       "id":1042,
       "item":19011,
       "name":"name 3",
       "description":null,
       "image":"http://images.jpg",
       "keywords":[
          "Florida Panthers",
          "NHL"
       ],
    },

輸入為“NHL”時的預期結果:

    {
       "id":1015,
       "item":19023,
       "name":"name 20",
       "description":"",
       "image":"http://images.jpg",
       "keywords":[
          "NHL",
          "Party"
       ],
    },
    {
       "id":1042,
       "item":19011,
       "name":"NHL® Florida Panthers® Slap Shot Cake",
       "description":null,
       "image":"http://images.jpg",
       "keywords":[
          "Florida Panthers",
          "NHL"
       ],
    }

我試過這樣的事情:

myArray.filter(x => x.keywords === searchFilter)

但它不會搜索關鍵字數組。

所以基本上我需要這樣的東西:

myArray.filter(x => x.keywords[loop through all indexes] === searchFilter)

最好的方法是什么?

檢查嵌套數組.includes是否包含您要查找的字符串:

 const myArray=[{id:1014,item:19021,name:"name 1",description:"",image:"http://images.jpg",keywords:["Cake","Party","Birthday"]},{id:1015,item:19023,name:"name 22",description:"",image:"http://images.jpg",keywords:["NHL","Party"]},{id:1042,item:19011,name:"name 3",description:null,image:"http://images.jpg",keywords:["Florida Panthers","NHL"]}]; const filtered = myArray.filter(item => item.keywords.includes('NHL')); console.log(filtered);

暫無
暫無

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

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