I use WeatherAPI’s service, which returns the weather forecast given the city name
The URL looks like this https://api.weatherapi.com/v1/forecast.json?key=[API_KEY]&q=tokyo&aqi=no
After trying to paste that URL into my browser and pasting the result into a JSON beautifier, here’s the result
Here’s the weird part. I tried using axios to fetch the information from my app and printing it out, this is what it gave me
It was unable to fetch forecastday
and instead gave me a [Object]
, which didn’t make any sense to me since it worked just fine on my browser
Here’s my code (sorry for the spaghetti formatting) https://pastebin.com/9eJQy5Bf
I tried reinstalling the library, using proxies but the result remained the same.
Advertisement
Answer
forecast.forecastday
is an object array, to access a property from a particular object, you have to specify the index of the object in the array.
For example if you want the date
property of the first object.
const data = { forecast: { forecastday: [{ date: "2022-04-03" }] } } const date = data.forecast.forecastday[0].date; // index [0] = first element console.log(date);
If you would have multiple days, you could loop over them or use a function like map()
to get the specific items.
const data = { forecast: { forecastday: [{ date: "2022-04-03", date_epoch: 123456789 }, { date: "2022-04-04", date_epoch: 123456789 } ] } } const dates = data.forecast.forecastday.map(({ date }) => { return { date } }); console.log(dates);