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

Twitch频道直播状态更新开发求助:遍历streamsJson匹配频道ID

搞定Twitch频道直播状态更新的小方案

没问题,我来帮你实现这个遍历匹配并更新状态的逻辑!下面分两种场景给你代码示例,你可以根据自己的实际情况选用:

场景1:在数据层面更新频道状态(比如前端数组/后端对象)

假设你已经拿到了Twitch返回的streamsJson数据,还有存储目标频道信息的数组,代码可以这么写:

// 第一步:定义你的目标频道ID列表(替换成你实际的频道ID)
const targetChannelIds = ["12345", "67890", "你的频道ID"];

// 第二步:从Twitch Channels接口获取的频道基础信息数组
let myChannels = [
  { id: "12345", name: "我的频道1", status: "离线" },
  { id: "67890", name: "我的频道2", status: "离线" },
  // ...其他频道
];

// 第三步:从Twitch Streams接口获取的直播流数据(也就是你的streamsJson)
const streamsJson = [
  { id: "stream_xxx", channel_id: "12345", title: "正在直播原神" },
  { id: "stream_yyy", channel_id: "99999", title: "别人的直播" },
  // ...其他直播流
];

// 先重置所有目标频道的状态为离线(避免上次状态残留)
myChannels.forEach(channel => {
  if (targetChannelIds.includes(channel.id)) {
    channel.status = "离线";
  }
});

// 遍历streamsJson,匹配目标频道并更新为「直播中」
streamsJson.forEach(stream => {
  // 找到对应频道
  const matchedChannel = myChannels.find(channel => channel.id === stream.channel_id);
  // 如果匹配到且是目标频道,更新状态
  if (matchedChannel && targetChannelIds.includes(stream.channel_id)) {
    matchedChannel.status = "直播中";
  }
});

// 现在myChannels里的目标频道状态已经更新完成啦
console.log(myChannels);

场景2:直接更新页面上的频道状态(用jQuery的情况)

如果你需要把状态直接更新到页面DOM元素里,比如每个频道的状态显示在ID为status-频道ID的元素中,可以这么写:

// 目标频道ID列表
const targetChannelIds = ["12345", "67890"];
// Twitch返回的streamsJson数据
const streamsJson = [/* 你的直播流数据 */];

// 先把所有目标频道状态设为离线
targetChannelIds.forEach(channelId => {
  $(`#status-${channelId}`).text("离线");
});

// 遍历直播流,把正在直播的频道状态改成「直播中」
streamsJson.forEach(stream => {
  const channelId = stream.channel_id;
  if (targetChannelIds.includes(channelId)) {
    $(`#status-${channelId}`).text("直播中");
  }
});

这样不管是数据层面还是页面显示,都能准确更新你目标频道的直播状态啦~

内容的提问来源于stack exchange,提问作者Hacene .N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:41:01