2

我的javascript代码中有这个:

function parsePerObject(data){
    // LOOP OBJECTS
    var content = "";
    $.each(data, function(key, value){ 
        content += "<li class='contentblock has-thumb'>";
        content += "<p><a href='/sessions/view/" + value.id + "'>" + value.name + "</p>";      
        content += "<p>" + value.starttime + " - " + value.endtime + "</p>";
        content += "<p>" + value.speaker + "</p>";             
    });

    $("#here").append(content);
}

我想遍历数据。数据是一系列这样的对象:

{
    "21114"
    {
        "id":"21114",
        "external_id":"",
        "sessiongroupid":"1844",
        "eventid":"5588",
        "order":"0",
        "name":"localStorage HTML5 Session",
        "description":"localstorage",
        "starttime":"2013-04-23 12:00:00",
        "endtime":"2013-04-23 13:30:00",
        "speaker":"",
        "location":"",
        "mapid":"0",
        "xpos":"0.000000",
        "ypos":"0.000000",
        "maptype":"plan",
        "imageurl":"",
        "presentation":"",
        "organizer":"0",
        "twitter":"",
        "allowAddToFavorites":"0",
        "allowAddToAgenda":"0",
        "votes":"0",
        "url":"",
        "venueid":"0"
    },
    "21116"
    {
        //etc
    },
    //etc
}

但现在我想根据日期对数据进行排序。有人知道我该怎么做吗?

4

1 回答 1

2

诀窍是将对象转换为数组,然后使用JavaScript 出色的 Array.sort 方法和自定义比较函数。

http://jsfiddle.net/2BY5x/1/

function parsePerObject(data){
    // Turn the data object into an array
    var dataArray = [];
    $.each(data, function (key, value) {
        dataArray.push(value);
    });

    // Sort data by starttime
    dataArray.sort(function (a, b) {
        if (a.starttime > b.starttime) {
            return 1;
        }
        if (a.starttime < b.starttime) {
            return -1;
        }
        return 0;
    });

    // LOOP OBJECTS
    var content = "";
    $.each(dataArray, function(i, item){
        content += "<li class='contentblock has-thumb'>";
        content += "<p><a href='/sessions/view/" + item.id + "'>" + item.name + "</p>";      
        content += "<p>" + item.starttime + " - " + item.endtime + "</p>";
        content += "<p>" + item.speaker + "</p>";             
    });

    $("#here").append(content);

}
于 2013-04-19T13:57:09.360 回答