JavaScript: How to loop through JSON objects with jQuery in an AJAX call

advertisements

I am having difficulty trying to learn this concept.

I have a JSON file with a list of hospitals, their address, hours and phone.

I want to make an AJAX call from JSON data and list the data onto the screen.

I can only get the first hospital to list, when I try to list the address only the address lists.

How can I write this using a loop that will list the objects and their properties?

Can someone explain this to me, please?

Please help -- thank you in advance.

JSON --

https://api.myjson.com/bins/b29r7

JS --

var url = 'https://api.myjson.com/bins/b29r7';

$.ajax({
    url: url,
    method: 'GET',
}).done(function(result){
    var data = result.surrey;
    for(var i=0; i<data.length; i++){
        $('#data').each(function(index, ele){
            $(ele).html(data[index].hospital);
        });
    }
}).fail(function(err){
    throw err;
});

HTML --

<p id="data"></p>


Here's a working example:

var url = 'https://api.myjson.com/bins/b29r7';

$.ajax({
  url: url,
  method: 'GET',
}).done(function(result) {
  // JSON data array
  var data = result.surrey;

  // get DOM node to be parent of child list nodes
  var $data = $('#data');

  // iterate through each object in JSON array
  data.forEach(function(item) {

    // create an unordered list node
    var $ul = $('<ul></ul>');

    // iterate through all the properties of current JSON object
    for (var field in item) {

      // append list item node to list node
      $ul.append(`<li>${field}: ${item[field]}</li>`);
    }

    // append list node to parent node
    $data.append($ul);
  });
}).fail(function(error) {
  console.error(error);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="data"></div>

JSFiddle Demo: https://jsfiddle.net/L6j8n17j/4/