1

我有一个以这种很长的形式返回给我的联系人列表。它根据输入顺序返回(第一组括号外的字段,缩进)。我遇到的问题是我希望它按 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 
4

2 回答 2

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/

于 2013-02-24T02:06:48.237 回答
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;
});
于 2013-02-24T02:12:55.710 回答