0

I am trying to access data from an array that is in an object as seen in my code below. I am able to access main temp okay but not 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

5
  • What do you mean by you can't acces? Do you get some kind of error? Commented Jan 14, 2021 at 2:35
  • I see you have a line with console.log(data); What is its output? Do you see the fields you want to extract? It could be that your data does not have those fields ... Commented Jan 14, 2021 at 2:36
  • Can you please convert the link to text? Commented Jan 14, 2021 at 2:36
  • @PayamV yes I get the same data that I have in the link (Accessing Data right below the code) as far as I can tell it does have the fields. Commented Jan 14, 2021 at 2:41
  • @periplo. No no errors, nothing appears on my page. Commented Jan 14, 2021 at 2:41

2 Answers 2

1

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. Here's the reference page for object destructuring assignment in javascript which can help explain how to use it.

Sign up to request clarification or add additional context in comments.

Comments

0

Maybe this will help you

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

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

Prints: "clouds"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.