【问题标题】:How do I get data from an array in an object within an object from an api如何从 api 对象中的对象中的数组中获取数据
【发布时间】:2020-05-21 19:25:08
【问题描述】:

我使用 OpenWeatherMap API 创建了一个简单的天气应用程序。架构如下:

{
  "coord": {
    "lon": -122.08,
    "lat": 37.39
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01d"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 282.55,
    "feels_like": 281.86,
    "temp_min": 280.37,
    "temp_max": 284.26,
    "pressure": 1023,
    "humidity": 100
  }...

我正在尝试访问包含数组的天气键中的值。这是我尝试过的:

let iconImage = '';
data.weather.map((description, icon) => {
   this.description.textContent += description;
   iconImage += icon;
});
this.icon.setAttribute('src', data.weather.icon);

descriptionicon 是变量,它们指向我的 html 代码中的 li 元素,我从 API 获得的数据应该进入这些元素。

我该如何以正确的方式做到这一点??

【问题讨论】:

    标签: javascript arrays json api fetch


    【解决方案1】:

    let data = {
      "coord": {
        "lon": -122.08,
        "lat": 37.39
      },
      "weather": [
        {
          "id": 800,
          "main": "Clear",
          "description": "clear sky",
          "icon": "01d"
        }
      ],
      "base": "stations",
      "main": {
        "temp": 282.55,
        "feels_like": 281.86,
        "temp_min": 280.37,
        "temp_max": 284.26,
        "pressure": 1023,
        "humidity": 100
      }
    };
    console.log(data.weather[0].icon);

    【讨论】:

    • 用于获取描述@Alessio Cantarella
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-06
    • 2018-01-24
    相关资源
    最近更新 更多