私はこのような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"
}]
オブジェクトのジャンル文字列を分割して、文字列の一部がジャンル配列に含まれているかどうかを確認できます。
このソリューションには、2つのアプローチがあります。
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; }
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加