如何用FlatMap、Map和Filter替代循环处理电影列表数据?
Got it, let's walk through how to replace traditional loops with JavaScript's functional methods (flatMap, map, filter) to process your movie list data cleanly.
First, let's restate your source data for clarity:
let movieLists = [{ name: "Instant Queue", videos: [ { "id": 70111470, "title": "Die Hard", "boxarts": [ { width: 150, height: 200, url: "http://cdn-0.nflximg.com/images/2891/DieHard150.jpg" }, { width: 200, height: 200, url: "http://cdn-0.nflximg.com/images/2891/DieHard200.jpg" } ], "url": "http://api.netflix.com/catalog/titles/movies/70111470", "rating": 4.0, "bookmark": [] }, { "id": 654356453, "title": "Bad Boys", "boxarts": [ { width: 200, height: 200, url: "http://cdn-..." } ] } ] }];
Let's say our goal is to extract an array of objects that contain each video's ID, title, and the URL of its 150px-wide boxart (we'll filter out boxarts that don't match this size). Here's how to do it with functional methods:
const processedMovies = movieLists // Step 1: Flatten nested video arrays into a single list of videos .flatMap(movieList => movieList.videos) // Step 2: For each video, keep only those that have a 150px-wide boxart .filter(video => video.boxarts.some(boxart => boxart.width === 150)) // Step 3: Transform each video into our desired structure .map(video => { // Find the specific 150px boxart for this video const boxart150 = video.boxarts.find(boxart => boxart.width === 150); return { videoId: video.id, title: video.title, boxartUrl: boxart150?.url }; }); console.log(processedMovies);
How this works:
flatMap: Instead of looping through each movie list and then each video inside it,flatMaptakes everyvideosarray from the movie lists and merges them into one flat array of video objects. This eliminates the need for nested loops.filter: We narrow down the videos to only those that have at least one boxart with a width of 150. Thesomemethod checks if any element in theboxartsarray meets the condition.map: We transform each filtered video into a new object that only includes the data we care about (video ID, title, and the correct boxart URL). We usefindto grab the exact boxart we need from the video's boxart list.
If your goal is slightly different (e.g., grabbing the smallest boxart, or all boxarts), you can adjust the filter and map logic accordingly—this pattern scales well for most data processing needs without messy loops.
内容的提问来源于stack exchange,提问作者Shmuel Niraev

