[英]How can I filter through my array which contains a key with multiple string values?
我有一個像這樣的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"
}]
您可以拆分對象的流派字符串,並檢查流派數組中是否包含某些字符串。
此解決方案采用兩種方法,
filterSome
獲取所有商品 filterEvery
匹配的所有項目。 主要區別是分別使用Array#some
和Array#every
。
function filterSome(array, genres) { return array.filter(function (item) { var keys = item.genres.split(/,\\s*/); return genres.some(g => keys.includes(g)); }); } function filterEvery(array, genres) { return array.filter(function (item) { var keys = item.genres.split(/,\\s*/); return genres.every(g => keys.includes(g)); }); } var array = [{ 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: "2014" }, { movie: "Avengers: Endgame", description: "The Avengers have a last stand against Thanos", director: "Anthony Russo", genres: "action", year: "2019" }]; console.log(filterSome(array, ['action', 'superhero'])); console.log(filterEvery(array, ['action', 'superhero']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.