I am making API request to local bus transit. I am getting the JSON object, which I needed. But when I am trying to access the stop
key inside that object. it says cannot read the property of undefined.
But when I check the object it is there to read.
error is in addDataToHtml
. I am new to JS please let me know what mistake I am making here.
const apiKey = 'XXXXXXXXXXXXXX';
const query = 'streets.json?name=henlow bay&';
const stops = 'stops.json?street='
let stopsArray;
let promises = [];
const mainDiv = document.querySelector('.main-container')
const stopSchedules = stopKey => {
return fetch(`${host}stops/${stopKey}/schedule.json?${apiKey}`)
}
const promise = json => {
json.stops.forEach(e => {
promises.push(stopSchedules(e.key))
})
return promises;
}
const addDataToHtml = jsonData => {
Promise.all(promise(jsonData))
.then(response => {
return stopsArray = response.map( e => e.json())
})
.then((response)=> {
console.log(response);
response.forEach(e =>{
console.log(e['stop-schedule'].stop.name);
})
})
}
fetch(`${host}${query}${apiKey}`)
.then((response) => response.json())
.then((responseData) => fetch(`${host}${stops}${responseData.streets[0].key}&${apiKey}`))
.then((stopsRespose) => stopsRespose.json())
.then((stopsJson) => addDataToHtml(stopsJson))
And the Json object I am getting here is below.
{
"stop-schedule": {
"stop": {
"key": 60433,
"name": "Northbound Henlow at Fultz",
"number": 60433,
"direction": "Northbound",
"side": "Farside",
"street": {
"key": 1717,
"name": "Henlow Bay",
"type": "Bay"
},
"cross-street": {
"key": 1400,
"name": "Fultz Boulevard",
"type": "Boulevard"
},
"centre": {
"utm": {
"zone": "14U",
"x": 630170,
"y": 5519519
},
"geographic": {
"latitude": "49.81398",
"longitude": "-97.19061"
}
}
},
"route-schedules": [
{
"route": {
"key": 94,
"number": 94,
"name": "Route 94 Whyte Ridge - Fort Garry",
"customer-type": "regular",
"coverage": "regular"
},
"scheduled-stops": [
{
"key": "11245829-34",
"cancelled": "false",
"times": {
"arrival": {
"scheduled": "2019-05-20T17:44:10",
"estimated": "2019-05-20T17:43:15"
},
"departure": {
"scheduled": "2019-05-20T17:44:10",
"estimated": "2019-05-20T17:43:15"
}
},
"variant": {
"key": "94-0-H",
"name": "to Henlow & Scurfield"
},
"bus": {
"key": 211,
"bike-rack": "false",
"wifi": "false"
}
},
{
"key": "11245818-34",
"cancelled": "false",
"times": {
"arrival": {
"scheduled": "2019-05-20T18:27:10",
"estimated": "2019-05-20T18:27:10"
},
"departure": {
"scheduled": "2019-05-20T18:27:10",
"estimated": "2019-05-20T18:27:10"
}
},
"variant": {
"key": "94-0-H",
"name": "to Henlow & Scurfield"
},
"bus": {
"key": 211,
"bike-rack": "false",
"wifi": "false"
}
}
]
}
]
},
"query-time": "2019-05-20T17:33:44"
}