How can I display every index from my JSON Fetched Files?

In the picture shown here, I have a series of Tables being displayed:

https://i.sstatic.net/YUZD1.png

The issue highlighted in red is that I want to show the Index of each JSON array as the Table number.

Below is the code snippet:

function getExternal() {
   fetch('https://kyoala-api-dev.firebaseapp.com/queue-group/5e866db4-65f6-4ef0-af62-b6944ff029e5')
      .then(res => res.json())
      .then((res) => {
         let reservationList = '';

         res.forEach(function (reservation) {
            reservationList += `
            <tr>
               <th scope="row">Table</th>
               <td class="text-center">${reservation.minCapacity} - ${reservation.maxCapacity}</td>
               <td class="text-center">${reservation.activeQueuesCount}</td>
            </tr>`;
         });
         document.getElementById('lists').innerHTML = reservationList;
      })
      .catch(err => console.log(err));
};

Answer №1

Essentially, to retrieve the current position of an item in the loop when using the forEach function, you can utilize the index parameter provided by the function.

Here is the updated code snippet:

function fetchExternalData() {
   fetch('https://kyoala-api-dev.firebaseapp.com/queue-group/5e866db4-65f6-4ef0-af62-b6944ff029e5')
      .then(res => res.json())
      .then((res) => {
         let reservationList = '';

         res.forEach(function (reservation, index) {
            reservationList += `
            <tr>
               <th scope="row">${index}</th>
               <td class="text-center">${reservation.minCapacity} - ${reservation.maxCapacity}</td>
               <td class="text-center">${reservation.activeQueuesCount}</td>
            </tr>`;
         });
         document.getElementById('lists').innerHTML = reservationList;
      })
      .catch(err => console.log(err));
};

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

Join the nested Observables array

I have an array that holds objects, each containing two properties where one is an observable value. let myArray = [{def: 'name1', value: EventEmitter_}, {def: 'name2', value: EventEmitter_}] My goal is to subscribe to the observables ...

My custom font is not compatible with the browser on my asp.net site

I'm having trouble embedding my own font in my .aspx file. Google Chrome and Firefox don't seem to support the font, while IE does. Can someone please provide guidance on how to successfully embed the font in an asp.net page? Below is my code: ...

Stop JavaScript Injection Attacks

Let's consider a scenario where a user inputs information into a form that is then submitted to the server using PHP. In the PHP code, we have: $data = $_POST['data']; // or $data = strip_tags(@$_POST['data']); I am curious t ...

Developing a personalized logging service in NestJs: capturing logs without directly outputting them

I am currently working on developing a NestJs service that will enhance a Logger. However, I am facing issues with achieving the desired output (e.g., super.warn(); see below for more details). I have followed a tutorial from the nestjs site, but unfortuna ...

Does Postgres have a similar feature to SQL Server's Open from rowset command that allows importing JSON files?

We are currently transferring code from a SQL Server database to a Postgres v16 database There is a sample file named 'temprj.json' with the following structure: temprj.json { "ChannelReadings": [ { "ReadingsDto": [ ...

Issue with ExpressJS Regex not correctly matching a path

I'm currently struggling with a simple regex that is supposed to match words consisting of letters (0-5) only, but for some reason it's not working as expected. Can anyone help me figure out the correct expression and how to implement it in Expre ...

Troubleshooting the issue of JavaScript not executing on elements with a specific CSS class

I am attempting to execute a JavaScript function on each element of an ASP.NET page that is assigned a specific CSS Class. Despite my limited knowledge of JavaScript, I am unable to determine why the code is not functioning properly. The CSS Class is being ...

Is there a way to implement an onclick event for every iframe within a document using jquery?

I have a webpage containing two iframes that can be switched using a selector. My goal is to implement an onclick event that will trigger a URL for specific <rect> elements within the iframes. After reading a helpful post on accessing iframe childr ...

How to access and extract data from nested dictionaries in JSON format

I have a lengthy JSON file that begins with {"requestId": "2", "records": { "totalRecords": 5, "currentPageSize": 5, "currentPageNumber": 1 ... I uploaded the file and stored it in a variable usin ...

Refreshing MongoDB data by utilizing values from an object

I am facing a challenge with my MongoDB collection structure: [ { "stock": "GOOGLE", "price": 0 }, { "stock": "FACEBOOK", "price": 0 } ] On the other hand, I have a Stock_P ...

Tips for incorporating JSON data from an API into your frontend interface

After following a tutorial on setting up an API with Express and PostgreSQL, I was able to successfully retrieve all my data in JSON format. However, I am now facing the challenge of using this data on the frontend of a website. The code snippets below ar ...

Preventing Cross-Site Scripting (XSS) when injecting data into a div

I am using Ajax to fetch data in JSON format and then parsing it into a template. Here is an example of the function: function noteTemplate(obj) { var date = obj.created_at.split(/[- :]/), dateTime = date[2] + '.' + date[1] + '. ...

Encoding a string for use in a URL

After receiving a JSON data object, I extract a string from it using the following code: NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 ...

Updating a single .jshintrc option for a folder

My project has a .jshintrc file at the root, containing the following settings: { "node": true, "smarttabs": true, "undef": true, "unused": true } While these settings work well for node-related code in my project, they are not suitable for brows ...

React and React Router are causing the login screen layout to persistently display

The MUI Theme Provider I have includes a Layout with Dashboard and Order screens. Even though the user hits the '/' endpoint, the Login Screen should be displayed instead of the Layout. -App.js <ThemeProvider theme={theme}> <Router> ...

The extent of locally declared variables within a Vue component

Within this code snippet: <template> <div> <p v-for="prop in receivedPropsLocal" :key="prop.id" > {{prop}} </p> </div> </template> <script> export default ...

Steps to access a JSON file in Angular.JS locally without utilizing a server

Below is the code for my controller: angular.module('navApp', []).controller('blogCtrl', function($scope, $http) { $http.get("../json/blogs.json").success(function(response) {$scope.blogs = response.blogs;}); }); I am trying to fi ...

Guide: Previewing uploaded images with HTML and jQuery, including file names

Any constructive criticism and alternative methods for accomplishing this task are welcomed. I am currently working on writing jQuery code that will allow users to preview file(s) without reloading the DOM. To achieve this, I have been using .append() to ...

Encountered a GSON error while expecting a String, but instead found an

I am currently using the Gson library to deserialize this object: [ { "_id": "53357a63138c2564feaf187f", "worktypes": [ { "name": "Type one" }, { ...

Eliminate HTML field based on checkbox status

I'm looking to dynamically remove HTML fields based on a Yes/No condition. I've shared the code below for better understanding. If Yes is selected, I want to hide the No Field/Input/Box and vice versa. function AutoCheck() { if (document.getEl ...