对日期进行排序并显示非重复日期

时间:2013-04-19 12:58:33

标签: jquery parsing object

我在我的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
}

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

1 个答案:

答案 0 :(得分:2)

诀窍是将对象转换为数组,然后将JavaScript's excellent Array.sort method与自定义比较函数一起使用。

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);

}