首页 > 解决方案 > Angular在另一个数组中获取json数组

问题描述

我有以下 JSON 结构:

{
  "daypart": [
    {
      "dayOrNight": [
        null,
        "N",
        "D",
        "N",
        "D",
        "N",
        "D",
        "N",
        "D",
        "N",
        "D",
        "N"
      ]
    }
  ]
}

我想要做的是到达里面的键数组narrative。但是每当我尝试获取这些密钥时,我都会得到预测undefined或预测[object Object]

代码

 async forcast(){
    this.http.get("xxxxxxxxxxxxxxx")

    .subscribe(data => {

      let f = data
      this.dforecast = f["daypart"]["narrative"]


      console.log("forecast "+ this.dforecast )


    })
  }

标签: arraysjsonangular

解决方案


f['daypart']是一个数组。因此,您需要通过它的索引来引用它。

this.dforecast = f['daypart'][0]['narrative'];

此外,不需要声明forcast()async方法,因为我们处理的是可观察对象,而不是基于 Promise 的响应。

forcast() {
 // rest of your cose 
}

推荐阅读