按键值重新排序Json数组

时间:2013-02-24 01:48:13

标签: javascript json

我有一个联系人列表,以这么长的形式返回给我。根据输入顺序(第一组括号外的字段,缩进)返回。我遇到的问题是我想通过displayName按字母顺序排序。因为那是在主要内部的自己的数组中,我无法通过它重新排序完整的数组。有人能搞清楚吗?谢谢。哦,它必须在JS中完成。

{
"0":
{"id":1,"rawId":null,"displayName":"Person 1","name":null,"nickname":null,"phoneNumbers":[{"type":"mobile","value":"phonenumb53534r","id":0,"pref":false}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null},
"1":
{"id":2,"rawId":null,"displayName":"Person 2","name":null,"nickname":null,"phoneNumbers":[{"type":"mobile","value":"phonenumber535345","id":0,"pref":false}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null},
"2":
{"id":3,"rawId":null,"displayName":"Person 3","name":null,"nickname":null,"phoneNumbers":[{"type":"mobile","value":"phonenumber47474","id":0,"pref":false}],"emails":null,"addresses":null,"ims":null,"organizations":null,"birthday":null,"note":null,"photos":null,"categories":null,"urls":null}, goes on for a couple hundred rows 

2 个答案:

答案 0 :(得分:3)

JavaScript中的对象本质上不是顺序的。如果你有一个数组,你可以使用它。否则,您必须自己将对象的外部部分转换为数组:

var arrayOfObj = [];

for (item in obj) {
    if (obj.hasOwnProperty(item)) {
        arrayOfObj.push(obj[item]);
    }
}

如果你能在之前那么你甚至可以获得JSON,那就更好了。完成后,您可以使用普通数组.sort方法

arrayOfObj.sort(function (a, b) {
    if (a.displayName < b.displayName) {
        return -1;
    }
    else if (a.displayName > b.displayName) {
        return 1;
    }
    return 0;
});

http://jsfiddle.net/ZcM7W/

答案 1 :(得分:0)

您需要将该responseText解析为JSON。但是,由于它作为对象字面值返回,因此您必须将其转换为数组。然后,您可以使用自定义比较器功能对其进行排序。

var json = JSON.parse(response), 
data = [];

for (key in json) {
 data.push(json[key]);   
}

data.sort(function (a, b) {
    return a.displayName > b.displayName;
});