Reputation:
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;
});
});
}
});
Upvotes: 0
Views: 102
Reputation: 613
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.
Upvotes: 1
Reputation: 796
Maybe this will help you
main = {
"weather": [
{
"id": 803,
"main": "clouds",
"description": "broken clouds",
"icon": "04n"
}
]
}
console.log(main["weather"][0]["main"])
Prints: "clouds"
Upvotes: 0