Generating an array in Javascript using JSON

I've been doing a lot of research, but I can't seem to find a solution that works for me. My goal is to retrieve the next four bus arrival times for a specific bus stop using an application that reaches out to an API returning JSON data. The issue I'm facing is that although I can see my request going out through Fiddler, I'm struggling to store the data in an array. Here's the current code I'm working with, attempting to format the returned data into a table without success.

My ultimate aim is to have a pop-up appear when users click on "Show me the next 4 bus arrival times," but for now, this code snippet serves as a test. If possible, I would appreciate assistance in getting the button to call this function and display a table with these values. Please let me know if you can help implement this feature within the existing code.

Here is the JSON Data:

[{"ARRIVAL":"01:23P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"01:53P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"02:23P","ROUTE":"208","DIR":"E"},
{"ARRIVAL":"02:53P","ROUTE":"208","DIR":"E"}]

And here is the Code:

<script>
function getTimes(stopNumber) {
        var busArrivalAPI = "http://blahblahblah/rtcTimes/" + stopNumber ";
        $.getJSON(busArrivalAPI, function(busArrivals) {
            var a = [];
            for (var i = 0; i < busArrivals.length; i++) {
                a[i] = [busArrivals[i].ROUTE, busArrivals[i].ARRIVAL, busArrivals[i].DIR];
                document.getElementById("results").createElement("TR");
                for (var b = 0; b < 3; b++) {
                    var x = document.createElement("TH");
                    var z = a[i][b];
                    var t = document.createTextNode(z);
                    x.appendChild(t);
                    document.getElementById('results').appendChild(x);
                };
            };
        });     
</script>

This is my DIV:

<div style="overflow-x:scroll; overflow-y:scroll;" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="title:'Bus Arrival Times', selected:true">
  <table id='results'>
    <tr>
      <th>Route</th>
      <th>Arrival Time</th>
      <th>Direction</th>
    </tr>
  </table>
</div>

UPDATE: After implementing the makeTable concept provided below, it successfully worked when coding the JSON data directly. However, I encountered cross-domain issues when trying to use $.getJSON. I'm unsure how to resolve this and ensure my $.getJSON request functions properly. Any guidance on resolving this issue would be greatly appreciated.

function getTimes(stopNumber) {

    // This is the API address I need to hit. Trying to figure out how to incorporate it and remove the hard-coded data.
    //var busArrivalAPI = "http://-----/rtcTimes/"+ stopNumber + "?jsoncallback=?";    

    function makeTable(busArrivals) {
      var results = document.getElementById("results");
      var rowCount = results.rows.length;
      for (var x=rowCount-1; x>0; x--) {
        results.deleteRow(x);
      }
      
      busArrivals.forEach(function(busArrival) {
        var tr = document.createElement('tr');
        var route = document.createElement('td');
        route.appendChild(document.createTextNode(busArrival.ROUTE));
        var arrival = document.createElement('td');
        arrival.appendChild(document.createTextNode(busArrival.ARRIVAL));
        var direction = document.createElement('td');
        direction.appendChild(document.createTextNode(busArrival.DIR));
        tr.appendChild(route);
        tr.appendChild(arrival);
        tr.appendChild(direction);
        document.getElementById('results').appendChild(tr);
      });
    }

    function getJSON(callback) {
      var data = [{"ARRIVAL":"05:23P","ROUTE":"201","DIR":"E"},
        {"ARRIVAL":"05:54P","ROUTE":"202","DIR":"E"},
        {"ARRIVAL":"06:33P","ROUTE":"203","DIR":"E"},
        {"ARRIVAL":"07:11P","ROUTE":"204","DIR":"E"}];
        callback(data);
    }

    getJSON(makeTable);
  };

Answer №1

One approach could involve creating a dedicated function to generate the table dynamically. The code might look something like this:

function generateTable(busTimes) {
    busTimes.forEach(function(busTime) {
        var tr = document.createElement('tr');
        var route = document.createElement('td');
        route.textContent = busTime.route;
        var arrival = document.createElement('td');
        arrival.textContent = busTime.arrival;
        var direction = document.createElement('td');
        direction.textContent = busTime.direction;
        tr.appendChild(route);
        tr.appendChild(arrival);
        tr.appendChild(direction);
        document.getElementById('results').appendChild(tr);
    });
}

var busTimingsAPI = 'http://example.com/busSchedule/' + stopID;
$.getJSON(busTimingsAPI, generateTable);

Within each iteration of the forEach loop, a new row is created and populated with data before being added to the DOM.

Answer №2

It appears that you are creating a TR element but failing to append it to the table. Instead, you are directly appending the TH elements to the table, which is not properly done.

function getTimes(stopNumber) {
    var busArrivalAPI = "http://blahblahblah/rtcTimes/" + stopNumber;
    $.getJSON(busArrivalAPI, function(busArrivals) {
        var table = document.getElementById('results');
        for (var i = 0; i < busArrivals.length; i++) {
            var rowData = [busArrivals[i].ROUTE, busArrivals[i].ARRIVAL, busArrivals[i].DIR];
            var row = document.createElement("TR");
            for (var j = 0; j < 3; j++) {
                var cell = document.createElement("TH");
                var content = rowData[j];
                var textNode = document.createTextNode(content);
                cell.appendChild(textNode);
                row.appendChild(cell);
            };
            table.appendChild(row);
        };
    });
}

Regarding the array named a, it seems unnecessary in this function. If your goal is simply to convert object properties into an array for iteration, a single-dimensional array should suffice instead of using a two-dimensional one like a. I have modified the code accordingly by replacing a with a single array.

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

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

Error: The function user.comparePassword does not exist or is not defined

I am facing an error that says TypeError: user.comparePassword is not a function. I have ensured that all dependencies are installed and the APP is linked to all the libraries. I tried using Postman to retrieve data, but it doesn't seem to be workin ...

Determining the parameter type for the directive

How can you specify the types of parameters for the directive in AngularJS? Which type should be used for & binding? Refer to ngdoc or jsdoc for an example code. UPDATE: I am looking for answers to the following questions * @param {<< What sh ...

Extract JSON elements from a massive document

Looking for a way to update a JSON file in C# by deleting specific data sets? Check out this example below: [ { "ID": "ID0000001", "Name": "ABCD", "Std": "4" }, { "ID": "ID5335355", "Name": "JKLM", "Std": "6" }, { "ID": "ID5353 ...

When the user initiates a fetch request, they will be directed to the POST page as a standard

Whenever I utilize fetch for a post request, I encounter an issue where the user is not redirected to the Post page as they would be with a regular form submission. My goal is to be able to direct the user to a specific location on the server side at app ...

Altering the "src" property of the <script> tag

Can the "src" attribute of a current <script> element be altered using Jquery.attr()? I believed it would be an easy method to enable JSONP functionality, however, I am encountering difficulties in making it operate effectively. ...

Error: Headers cannot be set once they have already been sent

My app.js file has the following code snippet: app.use(function(req, res, next){ if(!req.user){ return res.redirect('/login_'); } next(); }) Everything seems correct so far. In my route/index.js file, I have the following code: rout ...

Using the goBack function in React Router does not add the previous location to the stack

In React Router v4, I have a list page and a details page in my web application. I want to implement a 'Save and close' button on the details page that redirects the user back to the list page when clicked. However, I noticed that after the user ...

Adjusting the opacity of the background image in the section - focus solely on the background

This section is what I'm working on. <section ID="Cover"> <div id="searchEngine">hello</div> </section> I am trying to achieve a fade in/out effect specifically for the background image of the Cover section. T ...

Encountering an error with an unknown variable while attempting to access a value from a JSON object

I had second thoughts about asking this question for fear of receiving a down-vote, but after extensive research and hours of typing, I have decided to go ahead. My goal is to retrieve the values 37 and exampleoffice from a json object: {"officeId":37,"o ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

ng-if directive in AngularJs will not function properly if the condition text includes a space

I encountered an issue while attempting to set values in AngularJS UI grid based on the row.entity values. To address this, I created a cellTemplate that evaluates the row values and applies text styling accordingly. Code Snippet var statusTemplate=&apos ...

Utilizing Angular 9 with Jest for unit testing: simulating a promise, checking for method invocation afterwards

I'm in need of assistance as I am unsure how to mock a promise and verify that a method is called within the then() block. When I click on the save button of my form, my code appears as follows: // File: myComponent.ts save() { const myObject = n ...

The Node.js application is unable to execute due to the error: "View "error" could not be found in the views directory."

Currently, I am following a tutorial that covers the integration of social login with Passport and Node. You can find the tutorial here: Tutorial Link In line with the tutorial, I have started working on a project while utilizing Windows 10 operating syst ...

Tips for resolving the warning message: "Utilize a callback function in the setState method to reference the

I'm having an issue with this code fragment as ESLint is giving me a warning: "Use callback in setState when referencing the previous state react/no-access-state-in-setstate". Can someone help me resolve this? const updatedSketch = await ImageManipula ...

Ugly consequences arise as Gulp stumbles upon uncharted territory during the uglify

I'm experiencing an issue with my squish-jquery task. Every time I run it, I encounter the following error: Starting 'squish-jquery'... events.js:85 throw er; // Unhandled 'error' event ^ Error at new JS_Par ...

Express encountering a problem while rendering a new page following a fetch request

Issue with Fetching and Rendering DataURL I have configured an HTTP fetch request from the client side to send JSON data (a dataURL from a canvas) to the server. However, I am facing an error while trying to access it on the server side and render a new p ...

Using JavaScript to convert the text within a div into negative HTML code

I am working with this specific div: <div class="signs" id="signs" onclick="toggle()">&#43;</div> It currently displays the positive sign. I have set up a JavaScript function that is triggered when the div is ...

`Why setRequestHeader is essential for Ajax and XMLHttpRequest`

Should I ever manually specify the setRequestHeader as 'application/x-www-form-urlencoded' for an ajax POST request? Is it necessary to manually define the setRequestHeader as 'multipart/form-data' when uploading files via ajax? Do XMLH ...

Troubleshooting the Gutter Problem in jQuery Isotope and Masonry

Currently, I am utilizing the Isotope jQuery plugin. While it is a fantastic tool, I am encountering a minor issue with aligning items in masonry mode. The width of my container is 960px, and I aim to have 4 items perfectly aligned as if they were adhering ...