我正在循环一些JSON,并希望按最新日期显示DOM元素。我有一个数据日期属性。在将它们创建为DOM元素之前,我如何对数组中的每个对象进行排序?
我有以下内容 -
$.getJSON(ytapiurl, function(data) {
$.each(data.feed.entry, function(i, item) {
var pubdate = item['published']['$t'];
htmlString +='<div class="cursor col-sm-6 col-md-3 item" data-date="' + fulldate '">Video</div>';
console.log(new Date(pubdate).getTime());
});
});
答案 0 :(得分:1)
假设pubdate
是entry
数组中项目的属性,您可以在创建html之前对数组进行排序
$.getJSON(ytapiurl, function (data) {
data.feed.entry.sort(function (a, b) {
var fd1 = new Date(a.pubdate);
var fd2 = new Date(b.pubdate);
return fd1.getTime() - fd2.getTime();
})
$.each(data.feed.entry, function (i, item) {
var fulldate = new Date(pubdate).toLocaleDateString();
htmlString += '<div class="cursor col-sm-6 col-md-3 item" data-date="' + fulldate '">Video</div>';
});
});
答案 1 :(得分:0)
Trick是使用日期对象排序数组,而不是表示日期的字符串。
var articles = [
{pubDate: new Date(2000, 0, 1), desc:'one'},
{pubDate: new Date(1999, 0, 1), desc:'two'},
{pubDate: new Date(2002, 0, 1), desc:'three'},
{pubDate: new Date(2001, 0, 1), desc:'four'}
];
console.log(articles);
articles.sort(function(a,b){
return a.pubDate < b.pubDate; // set desc or asc here
});
articles.forEach(function(article){
console.log(article.pubDate,article.desc);
// Write to DOM here
});
返回
Tue Jan 01 2002 00:00:00 GMT-0600 (Central Standard Time) "three"
Mon Jan 01 2001 00:00:00 GMT-0600 (Central Standard Time) "four"
Sat Jan 01 2000 00:00:00 GMT-0600 (Central Standard Time) "one"
Fri Jan 01 1999 00:00:00 GMT-0600 (Central Standard Time) "two"