对 json 保留索引进行排序

Sort json preserving index

本文关键字:排序 索引 json 保留      更新时间:2023-09-26

我正在尝试对下面的json进行排序,但直到现在都找不到方法。我通过数据类型为 json 的 jQuery ajax 获得这个 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",
        },
    }
}

正如我在评论中写和引用的那样 - 属性没有顺序。创建一个单属性对象的数组,您可以对其进行排序。像这样:

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等的对象中,以便于访问。