-4

我在 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"
}
]
4

2 回答 2

2

假设您的结果数组称为数据,它看起来像这样:

data.sort(function(a,b){
   if (a.name > b.name) return 1;
   return -1;
});
于 2013-08-21T09:19:25.107 回答
0

上一篇文章不正确,因为 0 永远不会返回。这将适用于您的情况。

yourData.sort(function(a, b){
    if (a.name > b.name) {
         return 1
    }
    if (a.name < b.name) {
         return -1
    }
    else {
         return 0
    }
});
于 2013-08-21T09:39:00.993 回答