Antonio Laguna
Antonio Laguna

Reputation: 9292

Javascript ".each" isn't looping through array

Here I have a very strange issue in my code. I've tried to ask out of here but nobody seems to find the logic to this problem.

I'll paste my code:

$(document).ready(function(){
        var max = 5;
        var d = new Date();
        var today = $.format.date(d, 'yyyy-MM-ddTHH:mm:ss');
        d.setDate(d.getDate() - 1);
        var yesterday = $.format.date(d, 'yyyy-MM-ddTHH:mm:ss');
        var querys = {
            'upcoming' : 'https://www.google.com/calendar/feeds/user/private-magic-cookie/full?alt=jsonc&v=2&start-index=1&max-results='+ max +'&orderby=starttime&sortorder=ascending&start-min=' + today ,
            'previous': 'https://www.google.com/calendar/feeds/user/private-magic-cookie/full?alt=jsonc&v=2&start-index=1&max-results='+ max +'&orderby=starttime&sortorder=descending&start-max=' + yesterday
        };
        var items = [];             
        $.each(querys, function(key, val) {
            items[key] = [];
            var typeOfEvent = key;
            $.getJSON(val, function(data) {             
                $.each(data.data.items, function(key, val) {                    
                    var when = $.format.date(val.when[0].start, 'dd-MM-yyyy HH:mm');        
                    if (when.search('/:/') == -1) //If no hours where indicated at the event
                        when = when.replace(/(\d{4})-(\d\d)-(\d\d)/, '$3-$2-$1');
                    items[typeOfEvent].push('<li id="' + key + '">' + val.title + ': El ' + when + '</li>');            
                });
            });
        });
        console.log(items); 
        $.each(items, function(key, val){
        var append = $('<ul/>').text(val.join(''));
        $(append).appendTo('body');
    });

    });

So, the last portion, the one supposed to append the array as a list to the body doesn't do nothing. No errors, no execution of code there. The console.log you see before, outputs the array perfectly at the console...

So, what's the matter here?

Upvotes: 0

Views: 254

Answers (3)

Guffa
Guffa

Reputation: 700342

I see two problems with that loop:

  • You are using the .each method instead of the $.each method, so you are using the items array as if it was an array of DOM elements.

  • You are creating a string, but then you are using it as a jQuery object. There is no appendTo method in the String object.

You can use jQuery to create the element instead of creating HTML code to be parsed:

$.each(items, function (key, val){
  var append = $('<ul/>').html(val.join(''));
  append.appendTo('body');
});

Edit:

As the data is fetched with AJAX, the array will be empty when this code runs. You would have to put the code inside the callback instead, and make sure that it only runs for the last callback:

$(document).ready(function(){
  var max = 5, d = new Date();
  var today = $.format.date(d, 'yyyy-MM-ddTHH:mm:ss');
  d.setDate(d.getDate() - 1);
  var yesterday = $.format.date(d, 'yyyy-MM-ddTHH:mm:ss');
  var querys = {
    'upcoming' : 'https://www.google.com/calendar/feeds/user/private-magic-cookie/full?alt=jsonc&v=2&start-index=1&max-results='+ max +'&orderby=starttime&sortorder=ascending&start-min=' + today ,
    'previous': 'https://www.google.com/calendar/feeds/user/private-magic-cookie/full?alt=jsonc&v=2&start-index=1&max-results='+ max +'&orderby=starttime&sortorder=descending&start-max=' + yesterday
  };
  var items = {}, cnt = 0;
  $.each(querys, function(key, val) {
    items[key] = [];
    var typeOfEvent = key;
    cnt++; // count the requests
    $.getJSON(val, function(data) {             
      $.each(data.data.items, function(key, val) {                    
        var when = $.format.date(val.when[0].start, 'dd-MM-yyyy HH:mm');        
        if (when.search('/:/') == -1) //If no hours where indicated at the event
          when = when.replace(/(\d{4})-(\d\d)-(\d\d)/, '$3-$2-$1');
        items[typeOfEvent].push('<li id="' + key + '">' + val.title + ': El ' + when + '</li>');            
      });
      if (--cnt == 0) { // check for last request
        console.log(items); 
        $.each(items, function(key, val){
          $('<ul/>').html(val.join('')).appendTo('body');
        });
      }
    });
  });
});

Upvotes: 2

Vivek
Vivek

Reputation: 11028

this should solve your problem...

$(append).appendTo('body');

or 

$('body').append(append)

Upvotes: 1

Jon Grant
Jon Grant

Reputation: 11530

I think it should be:

$.each(items, function(key, val) {
    var append = '<ul>'+val.join('')+'</ul>';
    $(append).appendTo('body');
});

You're treating items as a selector, not an array. Also you have to surround the HTML you want to append with the jQuery function - there is no appendTo method on a plain old string :)

Upvotes: 4

Related Questions