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

新手求助:从JSON数组生成键值对(整合tvshowid、season、episode为键)

解决方案:从JSON数组生成自定义键值对结构

嘿,作为编程新手遇到这种结构化数据处理的问题很正常,我来一步步帮你搞定!

首先,咱们先理清你的需求核心:把每个剧集的tvshowid、season、episode三个字段用点连接成键,对应的值是episodeid,最终生成一个包含该键值对对象的数组。

步骤分解与代码实现

你的原数据结构外层是一个数组,里面的第一个元素包含了我们需要的episodes数组。我们可以用JavaScript的reduce方法来高效构建目标对象,代码如下:

// 假设你的原JSON数组已经存储在这个变量里
const originalArray = [ { "episodes": [ { "art": { "season.banner": "image://.jpg/", "season.poster": "image://.jpg/", "season.thumb": "image:.tbn/", "tvshow.banner": ".jpg/", "tvshow.fanart": "image:jpg/", "tvshow.poster": "image:jpg/" }, "episode": 1, "episodeid": 272, "file": "test.avi", "label": "test1", "originaltitle": "", "playcount": 0, "plot": "Hello World", "rating": 8, "season": 2, "thumbnail": "image.tbn/", "title": "test1", "tvshowid": 7 }, { "art": { "season.banner": "image://.jpg/", "season.poster": "image://.jpg/", "season.thumb": "image:.tbn/", "tvshow.banner": ".jpg/", "tvshow.fanart": "image:jpg/", "tvshow.poster": "image:jpg/" }, "episode": 2, "episodeid": 273, "file": "test1.avi", "label": "test1", "originaltitle": "", "playcount": 0, "plot": "Hello World", "rating": 8, "season": 2, "thumbnail": "image1.tbn/", "title": "test2", "tvshowid": 7 } ] } ];

// 1. 提取出需要处理的episodes数组
const episodes = originalArray[0].episodes;

// 2. 用reduce构建键值对对象
const episodeMap = episodes.reduce((acc, currentEpisode) => {
  // 拼接自定义键:tvshowid.season.episode
  const key = `${currentEpisode.tvshowid}.${currentEpisode.season}.${currentEpisode.episode}`;
  // 将episodeid赋值给对应的键
  acc[key] = currentEpisode.episodeid;
  return acc;
}, {});

// 3. 包装成你需要的数组结构
const newarray = [episodeMap];

// 打印结果看看
console.log(newarray);

代码解释

  • reduce方法:它可以帮我们遍历episodes数组,逐步构建出目标对象,比push更适合这种键值对的聚合场景。
  • 模板字符串:用`${a}.${b}.${c}`的方式可以轻松拼接出你需要的键格式,避免繁琐的字符串相加。
  • 最终结构:最后把生成的键值对对象放到数组里,就得到了你想要的[{7.2.1 : 272, 7.2.2 : 273}]结构(注:JavaScript中对象的键本质是字符串,所以实际输出里键会带引号,但使用时不影响)。

扩展说明

如果你的原数组里有多个外层对象(比如不止一个元素包含episodes),可以稍微调整代码来合并所有剧集的键值对:

// 遍历外层数组,合并所有episodes
const allEpisodes = originalArray.flatMap(item => item.episodes);
// 后续步骤和之前一样
const episodeMap = allEpisodes.reduce((acc, currentEpisode) => {
  const key = `${currentEpisode.tvshowid}.${currentEpisode.season}.${currentEpisode.episode}`;
  acc[key] = currentEpisode.episodeid;
  return acc;
}, {});
const newarray = [episodeMap];

这样不管原数组有多少个外层元素,都能统一处理啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:26:51