Question

I have the following dictionary of dictionaries, I have to use this format cuz I have no power over server side

{"1":{"aov":0,"oo":1,"ot":"Cem-Merve","pi":87},"2":{"aov":100,"oo":2,"ot":"Murat-Pelin","pi":88},"3":{"aov":0,"oo":3,"ot":"Fevzi-Azbiye","pi":85},"4":{"aov":0,"oo":4,"ot":"Burak-Gizem","pi":86},"21":{"aov":100,"oo":21,"ot":"Murat","pi":84,"ro":2},"22":{"aov":0,"oo":22,"ot":"Pelin","pi":83,"ro":2}}

I need to sort it with Javascript by keys alphabetically to be like

{"1":{"aov":0,"oo":1,"ot":"Cem-Merve","pi":87},"2":{"aov":100,"oo":2,"ot":"Murat-Pelin","pi":88},"21":{"aov":100,"oo":21,"ot":"Murat","pi":84,"ro":2},"22":{"aov":0,"oo":22,"ot":"Pelin","pi":83,"ro":2},"3":{"aov":0,"oo":3,"ot":"Fevzi-Azbiye","pi":85},"4":{"aov":0,"oo":4,"ot":"Burak-Gizem","pi":86}}

I've tried something like that but no hope:

function sortObject(o) {
    var sorted = {},
    key, a = [];

    for (key in o) {
        if (o.hasOwnProperty(key)) {
            a.push(key);
        }
    }

    a.sort();

    for (key = 0; key < a.length; key++) {
        sorted[a[key]] = o[a[key]];
    }
    return sorted;
}

any Ideas how can I perform that?

Was it helpful?

Solution

As others have pointed out in comments, an object's properties cannot be sorted. What you could do instead, is produce a sorted array of the objects properties, and iterate that array to access the objects properties in the order you wish. You basically already did this in your example code - you just tried to take it a step too far.

See jsFiddle

function getObjectKeysAlphabetical(obj) {
    var keys = [],
        key;

    for (key in obj) {
        if (obj.hasOwnProperty(key))
            keys.push(key);
    }

    keys.sort();

    return keys;
}

var obj = {}; //Your object here.
var keys = getObjectKeysAlphabetical(obj)
    i = 0, key = null, val = null;

//Iterate the array of sorted keys.
for (i = 0; i < keys.length; i++) {
    key = keys[i];
    val = obj[key]; //Get the value of the property here.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top