Alex Polo
Alex Polo

Reputation: 905

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"
}

Upvotes: 1

Views: 194

Answers (3)

nikc.org
nikc.org

Reputation: 16952

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1073988

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.

Upvotes: 3

2ndkauboy
2ndkauboy

Reputation: 9377

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.

Upvotes: -1

Related Questions