如何根据具体值对json数据进行排序?

时间:2016-08-31 05:16:43

标签: javascript jquery json sorting

我正在使用此代码获取以下Json数据

function nextDepartures(minutes=120)
{
var modeId = 0;
var stopId = 1042;
var limit = 2;

xhr(broadNextDeparturesURL(modeId, stopId, limit), broadNextDeparturesCallback);

var nowDate = new Date();
nowDate.setMinutes(nowDate.getMinutes()+minutes); 



for(var i =0; i < broadjson[0].values.length;i++) {
    var date = new Date(broadjson[0].values[i].time_timetable_utc);
    var minutes;
    if (date < nowDate) {
        if (date.getMinutes() < 10) {
            minutes = "0" + date.getMinutes();
        }
        else {
            minutes = date.getMinutes();
        }

    else  {

        document.getElementById("depart").innerHTML += "<tr>" +
            "<td width='30%'>" + date.getHours() + ":" + minutes + "</td>" +
            "<td>" + broadjson[0].values[i].platform.direction.line.line_number +
            " "
            + broadjson[0].values[i].platform.direction.direction_name + "</td>" +

            "</tr>";
    }
    }
}
}

作为回报我得到了这个数据

{
"values": [
{
"platform": {
"realtime_id": 0,
"stop": {
"distance": 0.0,
"suburb": "East Melbourne",
"transport_type": "train",
"route_type": 0,
"stop_id": 1104,
"location_name": "Jolimont-MCG",
"lat": -37.81653,
"lon": 144.9841
},
"direction": {
"linedir_id": 38,
"direction_id": 5,
"direction_name": "South Morang",
"line": {
"transport_type": "train",
"route_type": 0,
"line_id": 5,
"line_name": "South Morang",
"line_number": "250",
"line_name_short": "South Morang",
"line_number_long": ""
}
}
},
"run": {
"transport_type": "train",
"route_type": 0,
"run_id": 15716,
"num_skipped": 0,
"destination_id": 1041,
"destination_name": "Clifton Hill"
},
"time_timetable_utc": "2016-03-16T01:51:00Z",
"time_realtime_utc": null,
"flags": "",
"disruptions": ""
}
]
}

我想根据

对这些数据进行排序
values.platform.direction.line.line_number

表示首先显示最低行号,最后显示最高行号。我尝试过Javascript函数排序(a,b),但它不起作用。问题是

values.platform.direction.line.line_number

是一个字符串值。那么如何根据line_number对数组进行排序,而line_number以字符串的形式返回整数?

3 个答案:

答案 0 :(得分:3)

之前在stackoverflow中询问过类似的问题。看看这个链接。 How to sort JSON by a single integer field?

答案 1 :(得分:2)

使用parseInt解析作为字符串传入的数字,并使用javascript sort函数对数组进行排序,如下所示。

myArray.sort(function(a, b){
    var lineA = parseInt(a.line_number),
        lineB = parseInt(b.line_number);
    if(lineA < lineB)  return -1;
    if(lineA > lineB) return 1;
    return 0;
});

答案 2 :(得分:1)

您可以直接使用line_number的delta进行排序。减去两个部分的数字。

&#13;
&#13;
var data = {
        values: [
            { platform: { direction: { line: { line_number: "250" } } } },
            { platform: { direction: { line: { line_number: "150" } } } },
            { platform: { direction: { line: { line_number: "110" } } } }
        ]
    };

data.values.sort(function (a, b) {
    return a.platform.direction.line.line_number - b.platform.direction.line.line_number;
});

console.log(data);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;