首页 > 解决方案 > 循环遍历 JavaScript 对象和子对象

问题描述

我正在尝试遍历 API 的响应。到目前为止我的代码:

async function getStreams(gamename){ 
  let url = `https://api.twitch.tv/kraken/streams/?game=${gamename}`;
  const response = await fetch(url,{ method: 'GET', headers: headers});
  const json =  await response.json();
  var test = Object.values(json)
});

测试变量返回一个像这样的对象。

原始响应看起来像这样

由于我感兴趣的所有内容都在streams我不知道如何分离每个流然后检查每个方面,例如channels.language密钥。

我觉得我几乎拥有以下内容:

Object.values(json).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object 
  console.log(key)
});

但是,现在我需要更深入地了解密钥——<code>key.values,key[0]和任何类似的东西都行不通。我需要遍历这个指定键的所有内容并检查 if language === 'de',然后打印整个键/对象。由于language标签位于其中的另一个子对象channel中,因此我对使用什么感到困惑。

标签: javascriptarraysobject

解决方案


分解问题。streams是一个对象数组。您可以根据来自channel.

const germanChannels = streams.filter(stream => stream.channel.language === 'de');

推荐阅读