Reputation: 93
new to Javascript. Attempting to pull data from a weather API for a project but have run into an issue that I'm sure is simple to solve. Here is the data I've fetched already:
{coord: {…}, weather: Array(1), base: "stations", main: {…}, visibility: 9656, …}
coord: {lon: -76.13, lat: 43.04}
weather: Array(1)
0: {id: 500, main: "Rain", description: "light rain", icon: "10d"}
length: 1
__proto__: Array(0)
base: "stations"
main: {temp: 281.12, feels_like: 274.24, temp_min: 280.37, temp_max: 282.04, pressure: 1004, …}
visibility: 9656
wind: {speed: 8.2, deg: 310}
rain: {1h: 0.25}
clouds: {all: 90}
dt: 1587324361
sys: {type: 1, id: 5965, country: "US", sunrise: 1587291309, sunset: 1587340289}
timezone: -14400
id: 0
name: "Syracuse"
cod: 200
__proto__: Object
What I need to do is select "Rain" under the weather class. However, since it is inside of an array I do not know how to get it. For example, if I do
data.visibility
I will of course be returned with 9656. Yet if I do
data.weather.0
or even data.weather.["0"]
I will be met with the following error: Uncaught SyntaxError: Unexpected number. And even if I were to not get this error, how would I go about accessing the specific element "Rain" in the Array?
Sorry if this is an easy fix, just having trouble finding an answer due to the very specific wording whenever I search.
Upvotes: 1
Views: 67
Reputation: 799
If you need only the first element of an array, you can simply use an index to get the value data.weather[0].main
.
Or you can map an array via the Array method data.weather.map(item => item.main)
. You will get a customized array ["Rain"]
Upvotes: 3
Reputation: 455
You access it like this:
data.weather[0].main
where 0 is an integer describing the index of the element of the array.
Upvotes: 2