Skip to content Skip to sidebar Skip to footer

Re-order Json Array By Key Value

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 pro

Solution 1:

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;
    }
    elseif (a.displayName > b.displayName) {
        return1;
    }
    return0;
});

http://jsfiddle.net/ZcM7W/

Solution 2:

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;
});

Post a Comment for "Re-order Json Array By Key Value"