javascript - 尝试过滤具有属性值的对象数组,该属性值也是数组
问题描述
我在 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。
抱歉,有任何英语错误或问题不够清楚,我仍处于学习初期
解决方案
你必须使用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);
推荐阅读
- javascript - javascript 中的 map = {} 与 map = new Map()
- spring - Spring Boot:使用范围时无法解析匹配的构造函数:原型
- android - 如何在 kotlin 中使用 android studio 编辑或更新现有的 excel 文件
- c# - 在 Wix 中添加具有多个依赖项的自定义操作
- linux - “观看”并告诉它已经观看了多长时间
- javascript - 通过 FOR 循环将多个 Data 属性嵌入到 div
- git - Gerrit Change-Id 存在但仍然出错
- javascript - javascript中的输出元素如何放入数组中?
- azure - 在 azure 中,哪个是提供对 azure 存储帐户的限时访问的更好选择?
- arrays - MacOS - 使用 JSON 数组将条目添加到 SwiftUI 列表