Javascript 如何筛选包含多个字符串值的键的数组?
我有一个JSON文件,如下所示:Javascript 如何筛选包含多个字符串值的键的数组?,javascript,arrays,filter,Javascript,Arrays,Filter,我有一个JSON文件,如下所示: [{ "movie": "The Dark Knight", "description": "The caped crusader protects Gotham from new evil.", "director": "Christopher Nolan", "genres": "superhero, thriller, action", "year": "2008" }, { "movie": "IT Cha
[{
"movie": "The Dark Knight",
"description": "The caped crusader protects Gotham from new evil.",
"director": "Christopher Nolan",
"genres": "superhero, thriller, action",
"year": "2008"
}, {
"movie": "IT Chapter Two",
"description": "Pennywise returns once more 27 years later.",
"director": "Andrés Muschietti",
"genres": "horror, mystery",
"year": "2019"
}, {
"movie": "Avengers: Endgame",
"description": "The Avengers have a last stand against Thanos.",
"director": "Anthony Russo",
"genres": "action, superhero",
"year": "2019"
}]
function myfilter(genres) {
let myJSON = parseJSON();
var newArray = myJSON.filter(function (item) {
return item.genres === genres
});
console.log(newArray);
}
我想创建一个filter函数,它允许我过滤整个对象数组,并返回一个包含过滤对象的新数组。我的功能是这样的:
[{
"movie": "The Dark Knight",
"description": "The caped crusader protects Gotham from new evil.",
"director": "Christopher Nolan",
"genres": "superhero, thriller, action",
"year": "2008"
}, {
"movie": "IT Chapter Two",
"description": "Pennywise returns once more 27 years later.",
"director": "Andrés Muschietti",
"genres": "horror, mystery",
"year": "2019"
}, {
"movie": "Avengers: Endgame",
"description": "The Avengers have a last stand against Thanos.",
"director": "Anthony Russo",
"genres": "action, superhero",
"year": "2019"
}]
function myfilter(genres) {
let myJSON = parseJSON();
var newArray = myJSON.filter(function (item) {
return item.genres === genres
});
console.log(newArray);
}
问题是,此函数将适用于任何其他键,但不适用于“流派”键。我想给它一个输入,比如:myfilter(['action','superhero')代码>
并应返回:
[{
"movie": "The Dark Knight",
"description": "The caped crusader protects Gotham from new evil.",
"director": "Christopher Nolan",
"genres": "superhero, thriller, action",
"year": "2008"
},{
"movie": "Avengers: Endgame",
"description": "The Avengers have a last stand against Thanos",
"director": "Anthony Russo",
"genres": "action, superhero",
"year": "2019"
}]
您可以拆分对象的类型字符串,并检查类型数组中是否包含某些字符串
这个解决方案有两个特点
仅使用一种匹配类型获取所有项目
获取所有类型匹配的所有项目filterEvery
主要区别在于分别使用了
函数过滤器某些(数组、类型){
返回数组.filter(函数(项){
var key=item.genres.split(/,\s*/);
返回类型。一些(g=>keys.includes(g));
});
}
函数过滤器显示(数组、类型){
返回数组.filter(函数(项){
var key=item.genres.split(/,\s*/);
返回类型。每个(g=>keys.includes(g));
});
}
var array=[{电影:“黑暗骑士”,描述:“披着斗篷的十字军保护高谭免受新的邪恶之害。”,导演:“克里斯托弗·诺兰”,类型:“超级英雄,惊悚片,动作片”,年份:“2008”},{电影:“IT第二章”,描述:“27年后,便士又回来了。”,导演:“安德烈斯·马斯切蒂”,类型:“恐怖,神秘”,年份:“2014”},{电影:《复仇者:终局》,描述:“复仇者对塔诺斯的最后一站”,导演:“安东尼·鲁索”,体裁:“动作”,年份:“2019”};
log(filterSome(数组,['action','superhero');
log(filterEvery(数组,['action','superhero']);
.as控制台包装{max height:100%!important;top:0;}
JSON是一种文本格式,所以存在。您只是在筛选一个对象数组。是否要搜索两种类型(按参数移交)或者一个就足够了?我想能够为它提供任何字符串数组,并让它过滤所有内容谢谢,这非常有用。