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

如何将Movie API返回JSON中的影院与电影节点父子互换

嘿,这个问题我之前做电影场次相关项目时也碰到过!本质上就是要把API返回的「影片为核心」的JSON结构,重组为「影院为核心」的结构,核心思路就是遍历原始数据,以影院名称为键来聚合对应的影片和场次信息。我给你拆解一下具体怎么做:

先明确原始数据结构(模拟API返回)

假设你从API拿到的数据大概是这样的:

[
  {
    "title": "Black Panther",
    "showings": [
      {
        "theatre": "Main Street Cinema",
        "times": ["10:00 AM", "1:30 PM", "4:45 PM"]
      },
      {
        "theatre": "Downtown Multiplex",
        "times": ["11:15 AM", "2:30 PM"]
      }
    ]
  },
  {
    "title": "Avengers: Endgame",
    "showings": [
      {
        "theatre": "Main Street Cinema",
        "times": ["12:00 PM", "3:15 PM"]
      }
    ]
  }
]

用JavaScript实现结构转换

下面是具体的代码逻辑,你可以直接集成到你的项目里:

// 这里替换成你从API获取到的真实数据
const rawApiData = [/* API返回的JSON数据 */];

// 初始化一个空对象,用来存储以影院名为键的新结构
const theatreCentricStructure = {};

// 遍历每一部影片
rawApiData.forEach(movie => {
  // 遍历该影片的所有放映场次
  movie.showings.forEach(showing => {
    const theatreName = showing.theatre;
    
    // 如果当前影院还没在目标结构里,先创建基础条目
    if (!theatreCentricStructure[theatreName]) {
      theatreCentricStructure[theatreName] = {
        theatre: theatreName,
        movies: []
      };
    }
    
    // 把当前影片的标题和对应场次时间添加到该影院的列表中
    theatreCentricStructure[theatreName].movies.push({
      title: movie.title,
      times: showing.times
    });
  });
});

// 如果需要把对象转换成数组形式(更方便后续渲染或遍历),执行这一步
const theatreCentricArray = Object.values(theatreCentricStructure);

转换后的最终结构

运行上面的代码后,你会得到这样的结构,完全符合你要的「影院为父节点」的需求:

[
  {
    "theatre": "Main Street Cinema",
    "movies": [
      {
        "title": "Black Panther",
        "times": ["10:00 AM", "1:30 PM", "4:45 PM"]
      },
      {
        "title": "Avengers: Endgame",
        "times": ["12:00 PM", "3:15 PM"]
      }
    ]
  },
  {
    "theatre": "Downtown Multiplex",
    "movies": [
      {
        "title": "Black Panther",
        "times": ["11:15 AM", "2:30 PM"]
      }
    ]
  }
]

Python版本参考(如果你的项目用Python)

如果后端用Python处理,逻辑是一样的,只是语法不同:

# 替换成API返回的原始数据
raw_api_data = [/* API返回的列表数据 */]

theatre_centric_data = {}

for movie in raw_api_data:
    for showing in movie['showings']:
        theatre_name = showing['theatre']
        if theatre_name not in theatre_centric_data:
            theatre_centric_data[theatre_name] = {
                'theatre': theatre_name,
                'movies': []
            }
        theatre_centric_data[theatre_name]['movies'].append({
            'title': movie['title'],
            'times': showing['times']
        })

# 转换成数组格式
theatre_centric_array = list(theatre_centric_data.values())

额外注意事项

  • 如果API返回的影院名称有格式差异(比如大小写不同、前后空格),建议先做标准化处理(比如转成小写、去除首尾空格),避免生成重复的影院条目。
  • 如果需要处理大量数据,可以考虑用Map代替普通对象,性能会更优一些。

内容的提问来源于stack exchange,提问作者kimchi_is_life

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:41:12