开发者

Sorting an object?

How to sort this object lexicographically by its keys:

var obj = {'somekey_B' : 'itsval开发者_StackOverflow中文版ue', '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"
}


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜