[英]Filter array of objects with arrays nested by value
I'm trying to filter down results from a large array of objects.我正在尝试从大量对象中过滤掉结果。 Basically I have an input and I want to filter down the results when the input matches one or part of the keywords.
基本上我有一个输入,我想在输入匹配一个或部分关键字时过滤结果。
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"
],
},
Expected result if input is '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"
],
}
I tried something like this:我试过这样的事情:
myArray.filter(x => x.keywords === searchFilter)
But it doesn't search through the keyword array.但它不会搜索关键字数组。
So basically I need something like this:所以基本上我需要这样的东西:
myArray.filter(x => x.keywords[loop through all indexes] === searchFilter)
What's the best way to do this?最好的方法是什么?
Check if the nested array .includes
the string you're looking for:检查嵌套数组
.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.