【问题标题】:How to access a nested array from an API in typescript如何从 typescript 中的 API 访问嵌套数组
【发布时间】:2021-04-04 11:49:54
【问题描述】:

我有一组来自 API 的对象。看图

在我的 game.component.ts 中,我尝试访问主游戏数组中的一个数组,但我无法使用 typescript 访问平台名称(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中打印一个对象游戏的平台名称,每个游戏都有不同的平台名称。

我正在 typescript 中查找平台名称,以便稍后获取每个平台的 .png 图像。

【问题讨论】:

  • 为了帮助您,首先我需要知道向我们展示的屏幕截图是什么。那是“console.log(data)”吗?

标签: arrays angular typescript api


【解决方案1】:

所以,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
        }
}

【讨论】:

  • 但代码有效,但我需要所有游戏中对象游戏中每个平台的平台名称,不仅是第一个如何做 dinamyc data.results['this dinamyc'].platforms.forEach ...
  • 正如我所说,为了帮助您,我需要知道 getListGame 的订阅返回了什么(请提供屏幕截图)以及最重要的事情:您希望您的代码做什么。您缺少对目标的良好而清晰的描述。谢谢!
  • 侠盗猎车手 V 有 7 个平台 我需要在这个游戏中获得 7 个名称 其他游戏有 4 或 3 个平台
  • 发布于 = 平台
  • 好的。但是你想要得到的结构是什么?我的意思是你的要求是返回 20 个游戏,每个游戏都有几个平台。您要保存数据的结构是什么? this.GamesPlatform 是一个由 20 个元素组成的数组,其中每个元素都是一个平台数组就足够了吗?或者你到底需要什么?或者你想创建一个游戏数组[] 从请求的响应中提取信息?谢谢!
猜你喜欢
  • 2021-08-29
  • 2022-12-12
  • 1970-01-01
  • 1970-01-01
  • 2022-05-08
  • 2021-04-21
  • 2017-11-27
  • 2020-05-14
  • 2020-08-01
相关资源
最近更新 更多