tags:

views:

77

answers:

3
+1  Q: 

Sorting an object?

How to sort this object lexicographically by its keys:

var obj = {'somekey_B' : 'itsvalue', 'somekey_A' : 'itsvalue');

so that it outputs like this:

for (k in obj) {
  alert(k + ' : ' + obj[k]); //first "somekey_A : itsvalue"; then "somekey_B : itsvalue"
}
+3  A: 

You can't. The order in which for..in loops through the property names is implementation-specific and cannot be controlled. Your only alternative is to organize the properties yourself in some way, such as building an array of keys and then sorting it, e.g.:

var keys, index;

keys = [];
for (k in obj) {
    keys.push(k);
}
keys.sort();
for (index = 0; in dex < keys.length; ++index) {
  k = keys[index];
  alert(k + ' : ' + obj[k]); //first "somekey_A : itsvalue"; then "somekey_B : itsvalue"
}

You could, of course, put that in a function on the object and use it to iterate through the keys. Alternately, you could keep a sorted array on the object itself, provided you kept it up-to-date when you created new properties.

T.J. Crowder
Sure. So I thought to have the object sorted before looping. But how to do it - that's the question.
Alex Polo
I would just "sort" the array in PHP and be happy: sort($arr).
Alex Polo
@dfjhdfjhdf: The point is that you can't, not ir you're looping via `for..in`. That behavior (loop in sorted order) simply isn't defined in the language.
T.J. Crowder
No, not "loop in sorted order" but rather "loop a sorted thing".
Alex Polo
Darn JS. Though thanks for your kind reply.
Alex Polo
A: 

You need to copy the keys of the object into a sortable data structure, sort it, and use that in your for..in loop to reference the values.

var ob = {
    foo: "foo",
    bar: "bar",
    baz: "baz"
};

var keys = [];
for (key in ob) {
    keys.push(key);
}

keys.sort();
keys.forEach(
    function (key) {
     alert(ob[key]);
    }
);
nikc
I would love to! What is that sortable data structure?
Alex Polo
Any data structure that you can sort. I added an example.
nikc
A: 

If the object is an arrya (or you made it an array using Prototype, jQuery, etc) you can use the native array.sort() function. You can even use your own callback function for sorting the values.

Kau-Boy
He gave example code which shows that it *isn't* an array.
T.J. Crowder
(Not my downvote, btw.)
T.J. Crowder
I haven't seen the ":" in the object. And don't worry, I don't blame you for my bad answer :)
Kau-Boy