gpt4 book ai didi

javascript - 如何根据特定值对json数据进行排序?

转载 作者:行者123 更新时间:2023-11-29 19:10:31 25 4
gpt4 key购买 nike

我正在使用这段代码获取以下 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 函数 sort(a,b) 但它不起作用。问题是

values.platform.direction.line.line_number

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

最佳答案

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

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

关于javascript - 如何根据特定值对json数据进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39241268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com