我在Javascript中有这个对象:
[
{
"id": "60001",
"name": "NORTH COLORADO MEDICAL CENTER",
"friendly_name": "Kidney Failure - w/o CC MCC",
"address": "1801 16TH STREET",
"state": "CO",
"zip": "80631",
"service_count": "14",
"charges": "18,381",
"payments": "4,339",
"distance": "49.920"
},
{
"id": "60031",
"name": "CENTURA HEALTH-PENROSE ST FRANCIS HEALTH SERVICES",
"friendly_name": "Kidney Failure - w/o CC MCC",
"address": "2222 N NEVADA AVE",
"state": "CO",
"zip": "80907",
"service_count": "21",
"charges": "18,512",
"payments": "3,801",
"distance": "60.961"
}
]
默认情况下,对象按“id”排序。我想现在采用该对象,并按字段“名称”按升序排序,而不是“id”。 检查下面,看看我希望如何显示结果。
[
{
"id": "60031",
"name": "CENTURA HEALTH-PENROSE ST FRANCIS HEALTH SERVICES",
"friendly_name": "Kidney Failure - w/o CC MCC",
"address": "2222 N NEVADA AVE",
"state": "CO",
"zip": "80907",
"service_count": "21",
"charges": "18,512",
"payments": "3,801",
"distance": "60.961"
},
{
"id": "60001",
"name": "NORTH COLORADO MEDICAL CENTER",
"friendly_name": "Kidney Failure - w/o CC MCC",
"address": "1801 16TH STREET",
"state": "CO",
"zip": "80631",
"service_count": "14",
"charges": "18,381",
"payments": "4,339",
"distance": "49.920"
}
]
答案 0 :(得分:2)
假设结果数组被称为数据,它看起来像这样:
data.sort(function(a,b){
if (a.name > b.name) return 1;
return -1;
});
答案 1 :(得分:0)
上一篇文章不正确,因为永远不会返回0。这适用于您的情况。
yourData.sort(function(a, b){
if (a.name > b.name) {
return 1
}
if (a.name < b.name) {
return -1
}
else {
return 0
}
});