I have JSON I am getting from an API and once that data is fetched, I am using another API to get geocode values and adding that to the object.
Here is the initial object after fetching:
{ approved: 1
body: "sample comments being made. "
categories: (4) [{…}, {…}, {…}, {…}]
created_at: "2020-12-18T19:38:43.000000Z"
email: "janedoe@gmail.com"
geocode: null
id: 7
image_id: "7"
is_moderated: 1
updated_at: "2020-12-21T20:57:04.000000Z"
zip: "60611"
}
Then I am using this loop to use each object's zip to get Geocoding info and add it to each object.
for (const property in data) {
getLocationInformation(data[property]);
const allApprovedComments = createCommentElement(data[property]);
commentContentParent.append(allApprovedComments);
}
This is what the getLocationInformation
function looks like:
function getLocationInformation(comment) {
const fullPath = geoCode + '?address=' + comment.zip + '&key=' + geocodeApi;
fetch(fullPath)
.then(function fetchResponse(response) {
return response.json();
})
.then(function parseData(data) {
comment.geocode = {
county: data.results[0].address_components[2].long_name,
state: data.results[0].address_components[3].long_name,
stateAbbrv: data.results[0].address_components[3].short_name,
lat: data.results[0].geometry.location.lat,
lng: data.results[0].geometry.location.lng,
};
})
.catch(function fetchError(error) {
return error;
});
}
Then this is what the object that is returned:
{ approved: 1
body: "sample comments being made. "
categories: [{…}]
created_at: "2020-12-18T19:38:43.000000Z"
email: "janedoe@gmail.com"
geocode: {
county: "Cook County",
state: "Illinois",
stateAbbrv: "IL",
lat: 41.8925085,
lng: -87.61616959999999
},
id: 7
image_id: "7"
is_moderated: 1
updated_at: "2020-12-21T20:57:04.000000Z"
zip: "60611"
}
While, I am able to access the body
key and all others, even if console.log(object)
shows the geocode
key to have values when I try to access the key like: object.geocode
the value returned is always null
. I don't understand why this is happening and any help with getting past this issue is appreciated!