What's the best way to loop over an array in JSON?

167
November 22, 2016, at 09:18 AM

So I have a JSON file that has a departures array within it. I'd like to loop over each bus line and display them in div's like so:

<div class="bus">
    <div class="line">departure.line</div>
    <div class="direction">departure.direction</div>
    <div class="time">departure.time</div>
</div>

Each incoming bus has it's own bus div with all the related information inside it. I've gotten as far as displaying one of these, however I'm not sure how to iterate over them and display them in the correct places.

I'm open to utilizing vanilla JavaScript or jQuery.

Here's a jsfiddle with the array I want to iterate over: http://jsfiddle.net/tmm7b31w/

Answer 1

You need a foreach loop to simply go through the elements. See sample below:

$.each(item, function(index1, item1){
    var divContent = 
        '<div class="line">' + item1.line + '</div>' +
        '<div class="direction">' + item1.direction + '</div>' +
        '<div class="time">' + item1.aimed_departure_time + '</div>';
        $('#container').append(divContent);
});

I have updated your fiddle here.

Answer 2

You'll want to use a for each, like this:

HTML

<div class="bus prototype">
    <div class="line"></div>
    <div class="direction"></div>
    <div class="time"></div>
</div>

JavaScript (with jQuery)

var parent = $('body');
var prototype = $('.bus.prototype');
$.each(data.departures, function(index, departure) {
    var bus_div = prototype.clone();
    bus_div.find('.line').text(departure.line);
    //etc...
    parent.append(bus_div);
});

You could also do it with a vanilla JavaScript for loop.

for (var i = 0; i < data.departures.length; i++) {
    var departure = data.departures[i];
    var bus_div = prototype.clone();
    bus_div.find('.line').text(departure.line);
    //etc...
    parent.append(bus_div);
}
READ ALSO
bxSlider breaking after show()

bxSlider breaking after show()

I'm using bxSlider on ticker mode and have a pair of buttons that respectively hide and show it with.

240
jQuery show one next sibling at a time on click

jQuery show one next sibling at a time on click

I'm trying to show hidden rows one at a time on button click, but they all show at once since they have class "row" - the 1st row is shown by default and the rest are hidden.

162
jQuery Not Appending Object Values

jQuery Not Appending Object Values

So I'm currently building a random quote generator and whenever I try to append values from my object, it just returns:.

208
HighChartsDate Picker With Series Chart

HighChartsDate Picker With Series Chart

I'm attempting to use a jquery datepicker with a series chart from HighCharts. So far I've gotten the datepicker start and end date widgets working, however I'm having trouble with the actual implementation of the range selection.

202