JavaScript nested arrays not functioning with .map()

I've encountered a problem while using the .map function in JavaScript to extract a nested array from an API response.

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!",

Below is the code I included in 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> // encountering issues with this
      </div>
      </div>`;
    })
    .join("");

While item.title and item.start_time work perfectly, item.incident_updates.body does not seem to work at all, displaying as "Undefined" in my HTML file.

Any suggestions on how to properly render data from incident_updates.body?

Appreciate your help!

Answer №1

A crucial point to note is that incident_updates exists as an array, therefore requiring an index in order to access the correct element. To retrieve the desired element, consider utilizing the following approach with i representing the specific index:

var i = 0;
item.incident_updates[i].body

Answer №2

To iterate through the array item.incident_updates, you can utilize the map method

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>
  {item.incident_updates.map((data)={return(<p class="card-text">${data.body}</p>)})}
  </div>
  </div>`;
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to determine if an object.property is defined in Angular 2?

Is there a similar function in Angular 2 to angular.isDefined from Angular 1? I have tried using the safe navigation operator ?., which is only supported in templates. ...

Dim the background for all elements except for one

Seeking a way to create a dimmed-background effect by adjusting the opacity of all elements on the page except for one specific element. I've experimented with using the :not() selector as well as jQuery selectors to exclude certain elements, but have ...

Error: The post request was blocked due to cross-origin restrictions

This is my unique script /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ /** * Created by caneraydin on 16.03.2016. */ var app=angular.module('todoApp ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

Unable to successfully export ExpressJS routes to an external file when targeting the root path

I am seeking a way to organize my routes by exporting them into external files. Currently, all routes except the root route are functioning correctly: localhost/login -> "Login page" localhost/ -> empty server.js: // SERVER SETUP ============= v ...

Timeout error of 10000ms occurred while using await with Promise.all in Mocha unit tests

Document: index.ts // Default Exported Classes getItemsA() { return Promise.resolve({ // Simulating API call. Mocking for now. success: true, result: [{ itemA: [] }] }); } getItemsB() { return Promise.resolve({ // Simulating API cal ...

Concealing a feature across all pages of the website

I have implemented alert boxes that appear on all pages of the website. Users can individually close each alert box: $(document).ready(function() { $("#close-alert-box-news").click(function() { $("#alert-box-news").hide(800); }); $("#close-al ...

Is there a way to recognize each individual browser window that is presently open?

Is there a way to uniquely distinguish each separate browser window that is currently open across all major browsers using JavaScript? Let's examine the following scenario: I currently have 3 browser windows open, each with multiple tabs, in a modern ...

Utilizing JFlex for efficient brace matching

Currently, I am in the process of developing an IntelliJ plugin. One of the key features that I am working on is a brace matcher. After completing the JetBrains plugin tutorial, I was able to get the brace matcher functioning using this regular expression ...

Create a page turning effect in React that simulates scrolling a certain amount at a time

Is there a way to disable default scrolling and have the page automatically scroll to the next item? For example, if I have element2 below element1, how can I set it up so that when I scroll down once, the page scrolls directly to the position of element2 ...

angularJS controller does not seem to be functioning properly due to a certain

var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); var currentdate = yyyy + ',' + mm + ',' + dd; var appointmentDate = moment($scope.AppointmentsList[i].J).f ...

Validation of forms using Javascript

I currently have an HTML form with JavaScript validation. Instead of displaying error messages in a popup using the alert command, how can I show them next to the text boxes? Here is my current code: if (document.gfiDownloadForm.txtFirstName.value == &ap ...

Is there a way to automatically refresh a webpage whenever there are changes

Currently, I have a webpage that operates like a reverse auction, complete with a javascript countdown timer that tracks the time remaining in the auction. Once the timer reaches zero, the auction ends and the page automatically refreshes. While everythin ...

What is the best way to transfer the $http response value to another function?

I currently have these two functions set up. One function, $scope.submit, handles posting data to the server and capturing the response value. The other function, $scope.addTeams, is responsible for adding teams based on the response from $scope.submit. ...

Aurora MySQL causes PHP to stumble when encoding data into JSON

After transitioning my application from MySQL to Amazon Aurora's MySQL service, I encountered a challenge. The data retrieved from the database was used to search an Elasticsearch index through PHP's Elasticsearch library, which encodes query dat ...

Performing a dynamic animation by toggling the class of an element with "classList.toggle" in JavaScript

I have been attempting to incorporate a fade animation using CSS when altering the class of the input and label elements within a form by utilizing the classList.toggle method in JavaScript. I'm puzzled as to why my code isn't producing the desir ...

Automated user roster refresh

I have an online user list that is dynamically generated using a SQL query on a database table. How can I implement real-time updates to the webpage when a new user logs in? What specific code do I need to include for this functionality? Appreciate any g ...

Having trouble executing a jQuery function within AJAX-generated code

I may not be very experienced in JavaScript programming, but I am learning and trying my best to improve. Please excuse any errors I make along the way. Currently, I am attempting to use Ajax (not jQuery ajax) to save customer details, which then returns ...

What's the most effective method: Utilizing generic code generation or hardcoding API calls?

Currently, I find myself in a situation where I am contemplating the best practice for handling my work on an Ecommerce website that involves orders, shipments, invoices, and more. In addition to creating the UI for my application, I also have the capabil ...

Tips for successfully passing PHP variables to a JavaScript function

Having trouble passing the selected values of two comboboxes to another PHP file using AJAX. How can I pass both values in one function? <script> function showUser(str,str2) { if (str == "" || str2 =="") { document.getElementById("tx ...