I'm trying to access nested arrays in JavaScript from JSON returned from a weather app. However, I can't seem to access any of the data without the console returning cannot return property of 'x' of undefined
. I'm fairly certain that the problem lies in how I am interacting with the result
but I'm not sure. Does anyone know how I might properly access the data from within the nested array?
Here's my code that is currently not working:
const weather = require('weather-js');
var val;
var temp;
var final;
weather.find({search: 'Oceanside, CA', degreeType: 'F'}, function(err, result){
if (err) console.log(err);
obj = JSON.stringify(result, null, 2);
temp = result[2].current.temperature;
console.log(temp);
final = result[1].location.name;
console.log(final)
});
And here is the JSON I am trying to interact with:
[
{
"location": {
"name": "Oceanside, CA",
"lat": "33.197",
"long": "-117.381",
"timezone": "-8",
"alert": "",
"degreetype": "F",
"imagerelativeurl": "http://blob.weather.microsoft.com/static/weather4/en-us/"
},
"current": {
"temperature": "55",
"skycode": "31",
"skytext": "Mostly Clear",
"date": "2018-12-18",
"observationtime": "22:15:00",
"observationpoint": "Oceanside, CA",
"feelslike": "55",
"humidity": "90",
"winddisplay": "3 mph Southwest",
"day": "Tuesday",
"shortday": "Tue",
"windspeed": "3 mph",
"imageUrl": "http://blob.weather.microsoft.com/static/weather4/en-us/law/31.gif"
},
"forecast": [
{
"low": "46",
"high": "64",
"skycodeday": "29",
"skytextday": "Partly Cloudy",
"date": "2018-12-17",
"day": "Monday",
"shortday": "Mon",
"precip": ""
},
{
"low": "45",
"high": "65",
"skycodeday": "34",
"skytextday": "Mostly Sunny",
"date": "2018-12-18",
"day": "Tuesday",
"shortday": "Tue",
"precip": "0"
},
{
"low": "44",
"high": "67",
"skycodeday": "34",
"skytextday": "Mostly Sunny",
"date": "2018-12-19",
"day": "Wednesday",
"shortday": "Wed",
"precip": "0"
},
{
"low": "47",
"high": "69",
"skycodeday": "30",
"skytextday": "Partly Sunny",
"date": "2018-12-20",
"day": "Thursday",
"shortday": "Thu",
"precip": "0"
},
{
"low": "47",
"high": "65",
"skycodeday": "34",
"skytextday": "Mostly Sunny",
"date": "2018-12-21",
"day": "Friday",
"shortday": "Fri",
"precip": "0"
}
]
}
]
This question is not a duplicate of Access / process (nested) objects, arrays or JSON because as far as I can see the answers on that page dealt with arrays of more than a single element and this question did not.