【发布时间】:2019-09-13 20:04:45
【问题描述】:
我有一个这样的 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 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"
}]
【问题讨论】:
-
JSON 是文本格式,所以有no such thing as a JSON object。您只是在过滤一组对象。
-
你想同时搜索两种类型(通过参数传递)还是一种就够了?
-
我希望能够为它提供任何字符串数组并让它过滤所有内容
标签: javascript arrays filter