【问题标题】:How do I access the data returned by REST API in date-value format?如何访问 REST API 返回的日期值格式的数据?
【发布时间】:2020-10-10 16:55:19
【问题描述】:

我正在使用开放的 REST API (https://documenter.getpostman.com/view/11144369/Szf6Z9B3?version=latest#a9a60f59-fde4-4e94-b1f1-a3cb92bd1046) 在 Angular 中创建 Covid-Tracker 应用程序。

我想获取给定国家/地区过去 30 天的确诊病例数。响应如下所示:

在 Angular 中,我使用以下代码从 JSON 响应中获得 cases

covid.service.ts

  getHistoricalData(country: string): Observable<any> {
    return this.http.get<any>(`${this.URL}/historical/${country}`);
  }

dashboard.component.ts

  this.covidService.getHistoricalData('poland').subscribe(res => {
      let cases = res.timeline.cases;
      console.log(cases);
  });
  }

我在浏览器的控制台中得到以下输出:

但是,我不知道如何以键值对的形式保存这个输出,其中 key 是日期,value 是案例数在这一天。我试过使用Map,但我不知道如何提取给定的日期和相应的值。可以请教吗?

【问题讨论】:

    标签: json angular typescript rest


    【解决方案1】:

    您可以使用 Object.keys(your_object) 迭代该对象的键,如下所示,

    // data is timeline.cases
    let data = { "5/19/20": 100, "5/20/20": 200 };
    let newArray = [];
    Object.keys(data).forEach(key => {
        newArray.push({date: key, cases: data[key]});
    });
    console.log(newArray)
    

    您现在可以通过 newArray 上的 for 循环访问每个日期及其案例。 希望对您有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 2012-03-23
      • 2016-08-03
      相关资源
      最近更新 更多