按字母顺序排序JSON对象并返回JSON对象

时间:2013-07-24 20:36:43

标签: jquery sorting

我从cities.php发送一个像这样的json字符串:

[{"name":"Boston","len":1,"cid":"292"},{"name":"Miami","len":1,"cid":"243"},{"name":"Washington","len":1,"cid":"36"},{"name":"Alabama","len":1,"cid":"5"},{"name":"New York","len":1,"cid":"435"}]
然后我在我的cities.html中检索它,如下所示:

var cities = {};
$.getJSON('http://mypage.com/json/cities.php', function(data){ 
    $.each(data, function (k, vali) {
        cities[vali.cid] = vali.name;
    });
});

我正在使用json并放入一个javascript对象,它的工作方式非常完美,就像这样:

{ 
5: 'Alabama', 
36: 'Washington', 
243: 'Miamai', 
292: 'Boston',
435: 'New York'
};

这几乎没问题,但......不按字母顺序排列?

我需要在进入城市{}对象之前按名称对其进行排序...

我如何做到这一点?

希望得到帮助并提前感谢...

1 个答案:

答案 0 :(得分:1)

写一个比较函数

function compare(a,b) {
  if (a.name < b.name)
     return -1;
  if (a.name > b.name)
    return 1;
  return 0;
}

然后对数据进行排序

var cities = {};
$.getJSON('http://mypage.com/json/cities.php', function(data){ 
    data.sort(compare);
    $.each(data, function (k, vali) {
        cities[vali.cid] = vali.name;
    });
});