如何从打字稿中的 API 访问嵌套数组

时间:2020-12-27 11:23:58

标签: arrays angular typescript api

我有一个来自 API 的对象数组。看图片enter image description here

在我的 game.component.ts 中,我尝试访问主游戏数组中的数组,但无法使用打字稿访问平台名称(array7)。

  constructor(
    private gamesService:GamesService,
    private router: Router,
  ) {
    this.game = new Game('', '', [],  '', [], 1 );
    console.log(this.game);
    this.gamesService.getListGames(this.page).subscribe( (data: any) =>{
      //console.log(data.results);
      console.log(data);
      this.gameslist = data.results;
      //this.count = data.results.length;
      console.log(this.count);
      //this.nextpage = game.next;
      console.log(this.nextpage);
      console.log(data.results);
      if(data.platforms == 'PC')
      {
         return this.pcIcon= '../assets/pc.png';
      }
     });

如何访问 console.log(data.results " platform name" 中的platforms.name ????

在console.log中打印对象游戏的平台名称,每个游戏都有不同的平台名称。

enter image description here

enter image description here

我正在打字稿中寻找平台名称,以便稍后为每个平台获取 .png 图像。

1 个答案:

答案 0 :(得分:2)

因此,iiuc,API 将在“data.results”中返回一个包含 20 个游戏的数组。每个游戏都有一个“平台”数组。

要访问第一个游戏,您需要使用“data.results[0]”,而要访问游戏的第一个平台,您需要使用“data.results[0].platforms[0]”。 如果你想循环第一个游戏的平台,那么你的代码应该是这样的:

data.results[0].platforms.forEach((platform)=> { 
    if (platform == "PC") {
        //Your code here
    }
}

要循环播放所有游戏及其所有平台:

data.results.forEach((game) => {
    //Looping Platform for each game
    game.platforms.forEach((platform)=> { 
            //your code here
        }
}