首页 > 解决方案 > 尝试过滤具有属性值的对象数组,该属性值也是数组

问题描述

我在 json 中有这个对象:

{
"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。

抱歉,有任何英语错误或问题不够清楚,我仍处于学习初期

标签: javascriptecmascript-6

解决方案


你必须使用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);


推荐阅读