排序json保留索引

时间:2014-11-19 02:01:21

标签: javascript jquery ajax json sorting

我正在尝试对下面的json进行排序,但直到现在找不到方法。我用jQuery ajax和数据类型json得到了这个json。我怎样才能对索引进行排序?每次我尝试排序javascript抛出错误告诉undefined不是一个函数。我已经知道json或对象没有排序。

那我怎么能做到这一点?我真的需要保留这个索引。

{
    "header": {
        "user": "1059",
        "authenticated": true,
        "isGuest": false,
        "time": 1416362117
    },
    "batches": {
        "3503": {  // Preserve this index
            "user": "1059",
            "auction": "1826",
            "number": "1",
            "published": "1",
            "type": "1",
            "status": "1",
            "date_start": "1415379600",
            "date_end": "1417021200",  // Sort by this value
        },
        "3583": {
            "user": "1059",
            "auction": "1886",
            "auto_value": "0.00",
            "number": "1",
            "published": "1",
            "type": "1",
            "status": "1",
            "date_start": "1415376000",
            "date_end": "1417017600",
        },
    }
}

1 个答案:

答案 0 :(得分:0)

正如我在评论中所写和引用的那样 - 物业没有订单。创建一个可以排序的单属性对象数组。像这样:

var data = {
    "header": {
        "user": "1059",
        "authenticated": true,
        "isGuest": false,
        "time": 1416362117
    },
    "batches": [ // this is an array of objects, not a single object
        {"3503": {  // Preserve this index
            "user": "1059",
            "auction": "1826",
            "number": "1",
            "published": "1",
            "type": "1",
            "status": "1",
            "date_start": "1415379600",
            "date_end": "1417021200",  // Sort by this value
        }},
        {"3583": {
            "user": "1059",
            "auction": "1886",
            "auto_value": "0.00",
            "number": "1",
            "published": "1",
            "type": "1",
            "status": "1",
            "date_start": "1415376000",
            "date_end": "1417017600",
        }}
    ]  // end of array
}

data.batches.sort(function(a, b) {
    return a[Object.keys(a)[0]].date_end - b[Object.keys(b)[0]].date_end;
});

console.log(data.batches);

您可以将这些数字保存在包含userauction等对象的内部,以便于访问。