0

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>
illywilly
  • 323
  • 1
  • 5
  • 18
  • I think you're just looking for a loop over a JS object. – TankorSmash Apr 11 '17 at 16:35
  • for starters, `$('#data').each(` should be `$.each(data, function (index, elec) {...` – Adam Apr 11 '17 at 16:38
  • @Adam that doesn't work. – illywilly Apr 11 '17 at 17:02
  • Please update your question to ask something more specific if these comments / answers aren't helpful; you asked "How can I write this using a loop that will list the objects and their properties?" which @jencko shows you below... – Adam Apr 11 '17 at 17:10

3 Answers3

3

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/

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
  • Hi @MiguelMota thanks for the working example. Care to explain the set up to me? Please? For starters, I don't get why you wrote the function the way you did. Starting with-- data.forEach(function(item){...}); – illywilly Apr 11 '17 at 17:12
  • perfect. Thank you so much but i don't get your for loop set up. Is that new in ES2015? What is field and item as I do not see them defined. I tried to google this but wan't lucky with results. – illywilly Apr 11 '17 at 17:40
  • @scrippyfingers `forEach` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach `for..in` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in . – Miguel Mota Apr 11 '17 at 17:43
  • 1
    @scrippyfingers `forEach` iterates through all items in an array. The parameter `item` is the current item it's iterating over. `for..in` iterates through all the properties of an object. `field` is just a variable name for the object key it's iterating over, `item` is the object, `item[field]` is the object property value. – Miguel Mota Apr 11 '17 at 17:44
  • As for the line $ul.append(`
  • ${field}: ${item[field]}
  • `); Does ${ field } represent "interpolation"? I googled and found interpolation in JS with the syntax like so; #{ field } , so i am not sure.. @MiguelMota – illywilly Apr 11 '17 at 17:47
  • 1
    @scrippyfingers those are template literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals . (note you have to use backticks). They allow you to interpolate variable values inside of a string. Whatever is inside a `${}` gets evaluated to a value. That line is creating a list item with content and appending it the unordered list. – Miguel Mota Apr 11 '17 at 17:49
  • oh ok, i got it!! THANK YOU!! – illywilly Apr 11 '17 at 17:51