I am trying to return an object based on data coming from GET
request. I can print the whole object using console.log
but can't return the full object.
Please see my code below:
fetch('https://api-nile.tfl.gov.uk/AirQuality')
.then(function(response) {
return response.json();
})
.then(function(data) {
buildObjectDynamically(data);
});
function buildObjectDynamically(data) {
let airQualityObj = [];
for (let i of data.currentForecast) {
let eachEntry = {
id: i.$id,
forecastBand: i.forecastBand,
forecastType: i.forecastType,
};
airQualityObj.push(eachEntry);
}
console.log(airQualityObj);
return airQualityObj; // This line is not returning my object.
}
If I hardcode the data and leave outside the fetchAPI then it works as expected. Please see example below:
function buildStaticObject() {
return {
airQualityObj: [{
id: '2',
forecastType: 'Current',
forecastBand: 'Low',
},
{
id: '3',
forecastType: 'Future',
forecastBand: 'Low',
}
]
}
}
buildStaticObject();
Please note that I can actually return the response from the API. What I am struggling with is how to return the newly build object from that response.
Thanks