简体   繁体   English

访问 object 中数组中的数据

[英]Accessing data in an array within an object

I am trying to access data from an array that is in an object as seen in my code below.我正在尝试从 object 中的数组访问数据,如下面的代码所示。 I am able to access main temp okay but not weather main .我可以访问main temp okay 但不能访问weather main Please let me know what I am doing wrong.请让我知道我做错了什么。 Thank you.谢谢你。

See link for the data image.请参阅数据图像的链接。

let long;
let lat;
let temperatureDescription = document.querySelector(".temperature-description");
let temperatureDegree = document.querySelector(".temperature-degree");
let locationTimezone = document.querySelector(".location-timezone");

window.addEventListener("load", () => {
    let long;
    let lat;

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(position => {
            lon = position.coords.longitude;
            lat = position.coords.latitude;
            const proxy = "https://cors-anywhere.herokuapp.com/"
            const api = `${proxy}api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=d8c99fa56f1fcaaed3c5c9dd0cd52b72`
            fetch(api)
                .then(response =>{
                return response.json();
                })
                .then(data => {
                console.log(data);
                const {temp} = data.main;
                const {main} = data.weather[0].main;
                // set DOM Elements from the API
                temperatureDegree.textContent = temp;
                temperatureDescription.textContent = main;
            });
        });
    } 
});

Accessing data访问数据

Try changing the line to either尝试将行更改为

const main = data.weather[0].main

or要么

const { main } = data.weather[0]

What you did was equivalent to accessing data.weather[0].main.main which is undefined.您所做的相当于访问未定义的data.weather[0].main.main Here's the reference page for object destructuring assignment in javascript which can help explain how to use it.这是 javascript 中object 解构赋值的参考页,可以帮助解释如何使用它。

Maybe this will help you也许这会帮助你

main = {
    "weather": [
            {
                "id": 803,
                "main": "clouds",
                "description": "broken clouds",
                "icon": "04n"
            }
        ]
}

console.log(main["weather"][0]["main"])

Prints: "clouds"印花: "clouds"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM