我如何才能找到数组中所有具有像业余爱好一样的值的文档。例如,我怎么才能找到所有将滑雪作为爱好的用户,又是否有可能在一份声明中找到所有拥有高尔夫和足球的用户,或者我必须首先找到所有足球然后再寻找所有也支付高尔夫费用的用户,来减少阵列的数量? 基本过滤器不起作用,我发现的大多数示例仅涉及数组具有键/值对的情况。 在下面没有运气的情况下尝试过
constfilteredData = data.filter(x => x.hobby(e => e ==='ski')
[{ "user" : 1,
"name" : "demo 1",
"hobby" : ["soccer", "golf", "ski"],
"age" : 24
},
{ "user" : 2,
"name" : "demo 2",
"hobby" : ["soccer", "ski"],
"age" : 27
},
{ "user" : 3,
"name" : "demo 3",
"hobby" : [ "ski"],
"age" : 21
},{ "user" : 4,
"name" : "demo 4",
"hobby" : ["soccer", "golf"],
"age" : 24
}]
答案 0 :(得分:2)
您可以像这样使用filter
和includes
const data = [{
"user": 1,
"name": "demo 1",
"hobby": ["soccer", "golf", "ski"],
"age": 24
},
{
"user": 2,
"name": "demo 2",
"hobby": ["soccer", "ski"],
"age": 27
},
{
"user": 3,
"name": "demo 3",
"hobby": ["ski"],
"age": 21
}, {
"user": 4,
"name": "demo 4",
"hobby": ["soccer", "golf"],
"age": 24
}
];
const resSki = data.filter(({
hobby
}) => hobby.includes("ski"))
console.log(resSki)
const resSoccerGolf = data.filter(({
hobby
}) => hobby.includes("soccer") && hobby.includes("golf"));
console.log(resSoccerGolf)
答案 1 :(得分:0)
您还可以使用循环和开关,如果您搜索了多个内容,则不必遍历数组遍历数组。
const arr = [
{ user: 1, name: 'demo 1', hobby: ['soccer', 'golf', 'ski'], age: 24 },
{ user: 2, name: 'demo 2', hobby: ['soccer', 'ski'], age: 27 },
{ user: 3, name: 'demo 3', hobby: ['ski'], age: 21 },
{ user: 4, name: 'demo 4', hobby: ['soccer', 'golf'], age: 24 }
];
for (const item of arr) {
for (const hobby of item.hobby) {
switch (hobby) {
case 'ski':
console.log(`${item.name} likes to ski`);
break;
case 'soccer':
console.log(`${item.name} likes to play soccer`);
break;
}
}
}