how would I be able to iterate over this JSON api response to get the "body" object from "Incident_updates" array?
Here is the JSON:
[
{
"id": 3787,
"title": "Dummy title!",
"start_time": "2020-04-25T16:54:00.000Z",
"created_at": "2020-04-25T17:22:13.315Z",
"updated_at": "2020-04-25T17:32:15.364Z",
"incident_updates": [
{
"id": 9905,
"body": "Dummy Paragraph test!",
I have tried using .map and foreach in my script.js file but no matter what I try and do, nothing seems to work and I get a "undefined undefined" error in the console. I also need to get the incident_updates.body response from all arrays that were in the api response. doing something like incident_updates[0].body works however I also need the responses from incident_updates[1].body etc etc.
This is my script.js file
fetch(url)
.then((response) => {
if (!response.ok) {
throw Error("ERROR");
}
return response.json();
})
.then((data) => {
console.log(data);
const html = data
.map((item) => {
console.log(item.incident_updates[0]);
return `<div class="card card-space">
<div class="card-body">
<h5 class="card-title">${item.title}</h5>
<h6 class="card-subtitle mb-2 text-muted">${item.start_time}</h6>
<p class="card-text">${item.incident_updates.body}</p> // issues with this
</div>
</div>`;
})
.join("");
Thanks for your help!
incident_updatesis an array of object, you need to retrieve one of the items usingitem.incident_updates[0].body. If it has multiple elements, you should consider creating another loop and retrieve them.item.incident_updatesas well. How do you want each displayed within the HTML you're building?