【发布时间】:2016-02-19 15:41:33
【问题描述】:
在我提出这个问题之前,我已经搜索了StackOverflow,但我找不到我的案例的解决方案。
我从多个Facebook Graph API 调用中接收对象(见第一张图片)。
我想做的是按日期(event.start_time)对我的对象进行排序。
是否可以创建额外的数组?
对象的结构在第二张图片中可见。
变量“event”保存所有对象。
更新 我创建了一个全局数组并将所有事件对象推送到它,它现在是一个数组,所以它应该是可排序的。我就是不知道怎么做,请帮忙。
var arr = []; //global array to sort event objects
//function is called somewhere
function makeEvents(ids, infowindow, map, accessToken) {
var currentTime = dateFormat("date", new Date(), true);
//console.log(currentTime);
var display = document.getElementById("all");
var carousel = document.getElementById("carousel-inner");
// console.log(ids);
FB.api('/',
{ids : ids},
function (pages) {
if(pages) {
$.each(pages, function(page_key, page_value) {
var id = page_value.id;
//display.innerHTML += '<tr>';
//console.log(id);
//if date search changed, since date search input
FB.api('/'+ id +'/events?access_token='+ accessToken +'&since='+ currentTime, function (events) { //&offset=0 &until=2016-02-31
//console.log(events.data);
if(events) {
//console.log(events.data)
$.each(events.data, function(events_key, events_value) {
FB.api('/'+ events_value.id + '?fields=id,name,cover,description,start_time,place,ticket_uri,picture', function (event) {
if(event) {
//console.log(event);
arr.push(event);//fill array
}
});
});
}
});
// display.innerHTML += '</tr>';
});
}
});
}
console.log(arr);
arr.sort(function(a, b){
if(a.start_time < b.start_time)
return -1;
if(a.start_time > b.start_time)
return 1;
return 0;
});
这应该不起作用,因为我在数组中的深度不够。
已解决必须使用超时功能,因为数组在完全填充之前排序,这让我觉得它根本没有排序。如果有更好的方法来检查数组是否完成填充,请告诉我:)
setTimeout(function(){
arr = arr.sort(function (a, b) {
return a.name.localeCompare( b.name );
});
console.log(arr);
}, 5000);
【问题讨论】:
-
您还没有阵列?如果你这样做了,那么这对于内置的排序和比较器功能来说应该是微不足道的。
标签: jquery json sorting date object