Johnny
Johnny

Reputation: 67

Create an array from JSON in Javascript

I've researched quite a bit on here and I can't seem to find something that will work for me. What I have is an application that I'm trying to have go out and return the next four bus arrival times for a bus stop. I am reaching out to an API that returns this data in a JSON file. The problem I am having is I can see my request go out via fiddler but I can't seem to get the data into an array. Below is the code that I'm dealing with right now. I'm trying to get the returned data into a table format which you can see I'm failing at.

Eventually I want to get a popup to appear when the user clicks on the Show me the next 4 bus arrival times but this was for testing purposes. I would love to have the users click on my button which calls this function and then something like a like table open with these values. If you can help with that within this code I would appreciate it as well.

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"}]

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>

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: Ok, I've use the makeTable idea provide below and it works when I program as seen below hard coding the json data. However, when trying to use the $.getJSON I'm having some cross domain issues now and don't know how I can get my $.getJSON request working. Any input on how to get the data from my getJSON request work be great.

function getTimes(stopNumber) {

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

    function makeTable(busArrivals) {
    // This will remove old values so table will only load current Times
      var results = document.getElementById("results");
      var rowCount = results.rows.length;
      for (var x=rowCount-1; x>0; x--) {
        results.deleteRow(x);
      }
      //  This will populate the result table with the correct bus routes/times/direction
      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);
  };

Upvotes: 3

Views: 116

Answers (2)

Barmar
Barmar

Reputation: 782488

You're creating a TR element, but never appending it to the table. Instead, you're appending the TH elements directly to the table, which is invalid.

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 a = [busArrivals[i].ROUTE, busArrivals[i].ARRIVAL, busArrivals[i].DIR];
            var row = document.createElement("TR");
            for (var b = 0; b < 3; b++) {
                var x = document.createElement("TH");
                var z = a[b];
                var t = document.createTextNode(z);
                x.appendChild(t);
                row.appendChild(x);
            };
            table.appendChild(row);
        };
    });
}

I'm not sure why you need the a array. If you just want to change get the object properties into an array so you can iterate over it, you can do that with a 1-dimensional array, you don't need to save all the other rows in a 2-dimensional array. I've changed a to a single array.

Upvotes: 1

Jeferson Le&#227;o
Jeferson Le&#227;o

Reputation: 21

I think you could write a separate function to build the table, like this:

function makeTable(busArrivals) {
    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);
    });
}

var busArrivalAPI = 'http://blahblahblah/rtcTimes/'+ stopNumber;
$.getJSON(busArrivalAPI, makeTable);

In each iteration of the forEach loop, you construct a tr element, insert the tds and finally put the whole thing inside the DOM.

Upvotes: 2

Related Questions