簡體   English   中英

嘗試過濾具有屬性值的對象數組,該屬性值也是數組

[英]Trying to filter an array of objects that has a property value that is also an array

我在 json 中有這個 object:

{
"group": "A",
"id": "50"
"person": [
    {
      "name": 'Joe',
      "age": '29'
      "hobbies": ["Watching movies", "Gaming"]
    },
    {
        "name": 'Jessie',
      "age": '27'
      "hobbies": ["Gaming", "Reading"]
   }
    ]
}

我想按他們的愛好過濾人們。 例如,如果我按 Gaming 過濾,我需要用 Joe 和 Jessie 創建一個對象數組。 如果我按閱讀過濾,那么數組將只有 Jessie。

這是我的代碼:

    import { people } from '../../../data/index' // this is the json I shower above

    let filteredArray;
  filteredArray = people.filter(person => {
    return person.hobbies == "Gaming";
  })

這不起作用,但如果將愛好更改為 json 上的單個單詞,如下所示:

    {
        "name": 'Jessie',
      "age": '27'
      "hobbies": "Gaming"
   }

然后它工作得很好。

那么有沒有辦法使用帶有一系列愛好的過濾器來檢查其中一個值是否符合我的條件?

我只使用香草 Js,我只想支持 chrome。

抱歉,有任何英語錯誤或問題不夠清楚,我仍處於學習初期

您必須使用includes方法。 因為您正在嘗試在數組中搜索:

const filteredArray = people.filter(person => {
    return person.hobbies.includes("Gaming");
})

 const data = { group: 'A', id: '50', person: [ { name: 'Joe', age: '29', hobbies: ['Watching movies', 'Gaming'] }, { name: 'Jessie', age: '27', hobbies: ['Gaming', 'Reading'] } ] }; const result = data.person.filter(el => el.hobbies.includes('Gaming')); console.log(result);

暫無
暫無

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

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