You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用FlatMap、Map和Filter替代循环处理电影列表数据?

Using flatMap, map, and filter to Process Movie Data (Instead of Loops)

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, flatMap takes every videos array 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. The some method checks if any element in the boxarts array 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 use find to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:17:55