2013-09-23 48 views
0

我有以下腳本,它結合了2提要在一起:排序JSON數據客戶端

$(document).Ready(function() { 
    url = 'feed 1'; 
    url_2 = 'feed 2'; 

    $.when(
     $.ajax({ 
      type: "GET", 
      url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url), 
      dataType: 'json' 
     }), 
     $.ajax({ 
      type: "GET", 
      url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url_2), 
      dataType: 'json' 
     }) 
    ).done(function(a1, a2) { 
     var data = a1[0].responseData.feed.entries.concat(a2[0].responseData.feed.entries); 
     if (data[0]) { 
      for (i = 0; i <= data.length - 1; i++) { 
       document.write(data[i].title); 
       document.write("<br>"); 
       document.write(data[i].categories[0]); 
       document.write("<br>"); 
       document.write(data[i].publishedDate); 
       document.write("<br>"); 
       document.write(data[i].link); 
       document.write("<hr>"); 
      } 
     } 
     else { 
      document.write("No records"); 
     } 
    }); 
}); 

我該如何去有關publishedDate排序加入供稿?

我想我應該使用jquery.sort,但不知道如何使用它與我目前的代碼。

回答

1

你可以做這樣的事情

data.sort(function (a, b) { 
    if (a.v > b.v) { 
     return 1 
    } 
    if (a.v < b.v) { 
     return -1 
    } 
    return 0; 
}); 

注意

  • 變化v所公佈的數據
  • data的變量名應該是飼料的數組
+0

Thi似乎給了我奇怪的結果,即2013年8月12日,2013年12月16日,2013年5月12日。我期待2013年12月16日,2013年8月12日,2013年5月12日。 – oshirowanen

+0

@oshirowanen將'return 1'改爲'return -1',反之亦然 – Johan

+0

似乎仍然是完全隨機的,即在同一個月和一年中,我得到2013年9月19日,22日,15日,然後是2013年5月12日? – oshirowanen