1

I have a contact list that is returned to me in this very long form. It is getting returned Based on order of entry (the field outside the first set of brackets, indented). The problem I'm having is I want it to order alphabetically by displayName. Since that is in it's own array inside of the main one I'm having trouble getting the full array to reorder by it. Can anyone figure this out? Thanks. Oh and it's got to be done in 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 
1
  • These are object, not arrays. Objects do not have any set order .. do you want to store the nested objects inside of an array in order? Commented Feb 24, 2013 at 2:04

2 Answers 2

3

Objects in JavaScript are not ordinal by nature. If you have an array, you can work with that. Otherwise, you have to convert the outer part of the object into an array yourself:

var arrayOfObj = [];

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

If you can do that before you even get the JSON, so much the better. Once you have that, you can just use the normal array .sort method

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/

Sign up to request clarification or add additional context in comments.

Comments

0

You'll need to parse that responseText into JSON. But since it's returned as an object literal you'll have to convert it to an array. Then you can sort it with a custom comparator function.

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.