【问题标题】:How to loop through array of objects in angular 6?如何循环遍历角度 6 中的对象数组?
【发布时间】:2021-08-31 09:46:55
【问题描述】:

我对 Angular 很陌生,我被分配了一项任务,我想从 API 获取数据并迭代并在图表中显示它。我的角度版本是 6。

这是响应 JSON 格式,它是一个对象列表-

[
    {
        "counts": 0,
        "time": "00:00:00"
    },
    {
        "counts": 0,
        "time": "01:00:00"
    },
    {
        "time": "02:00:00",
        "counts": 1
    },
    {
        "counts": 7,
        "time": "03:00:00"
    }
]

获取那个

 data : [];

this.service.getPaymentDistributionData()
    .subscribe((res) => {
      console.log(res)
    })

如何获取每个计数和时间并打印?

谢谢,

【问题讨论】:

标签: angular angular6 subscribe


【解决方案1】:
this.service.getPaymentDistributionData()
.subscribe((res) => {
    res.forEach(x => console.log(x.count))
})

对 res = [{}, {}] 的对象数组尝试这样的事情

对于res = {}的对象

Object.keys(res).forEach((key) => )

【讨论】:

  • 我在这里遇到的同样问题,比如“对象”类型上不存在属性“forEach”。
  • 好的,它应该在对象数组上完美工作我认为如果它只有对象或对象数组,你应该再次检查你的数据。
  • 它的对象数组
  • 请参阅我在返回类型问题中已注明
  • 我得到了你的答案,我将它稍微修改为 res: any[],然后它就起作用了
【解决方案2】:

你可以使用.. of

for (let ct of res) {
     console.log(ct.counts);
     console.log(ct.time); 
}

【讨论】:

  • 这里我收到一个错误,例如 Type 'Object' is not an array type 或 string type。那是什么。
  • 您的服务可能返回一个对象,而不是一个数组。
猜你喜欢
  • 1970-01-01
  • 2017-02-04
  • 2016-09-07
  • 1970-01-01
  • 2021-08-27
  • 2023-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多