0

The enumeration of JS objects seems to be inconsistent in Firefox.

Code:

var a = {"3":"a", "2":"b", "foo":"c", "1":"d"};

var str = "";
for(var n in a) { str += n + " = " + a[n] + "\n"; }
alert(str);

Result with FF22 on Windows:

1 = d
2 = b
3 = a
foo = c

Result expected (and what I get with FF20 on Linux):

3 = a
2 = b
foo = c
1 = d

How can I keep the Elements in the same order as inserted?

I know the ECMA specification doesn't say how the enumeration should be done, therefore it can't be called a bug. But I need the elements in the order inserted. (Reason: I get a JSON-encoded hash-table which is ordered server-side. Until recently the order was kept, now the whole list is a mess because it's ordered by the keys)

  • possible duplicate of [Associate Array / Key Pair Array In Javascript arranged in with random order of keys.](http://stackoverflow.com/questions/17444480/associate-array-key-pair-array-in-javascript-arranged-in-with-random-order-of) – Sirko Jul 12 '13 at 14:23
  • 1
    There is nothing you can do. – RoToRa Jul 12 '13 at 14:23
  • 1
    Well, there is *something* you can do. Stop trying to make an unordered collection ordered, and use an array instead. – cHao Jul 12 '13 at 14:24
  • @Sirko: You're right, didn't find that one. But anyway, it doesn't solve my problem – user1120146 Jul 16 '13 at 15:35

1 Answers1

2

No, you can't get that. The order of keys in object is undetermined and can be anything JS implementation wants.

You can, however, sort the keys:

var a = {"3":"a", "2":"b", "foo":"c", "1":"d"};

var str = "";
for(var n in Object.keys(a).sort(your_sorting_function)) {
  str += n + " = " + a[n] + "\n";
}
alert(str);

your_sorting_function should accept two arguments, which effectively will be names of the keys in a object. Then this function should return 0 for identical keys, 1 if the first key is considered "bigger" and -1 otherwise.

Object.keys() does not exist in all the browsers, but there's plenty of implementations that can be found.

For example:

Object.keys = Object.keys || function(o) {  
    var result = [];  
    for(var name in o) {  
        if (o.hasOwnProperty(name))  
          result.push(name);  
    }  
    return result;  
};
mishik
  • 9,973
  • 9
  • 45
  • 67
  • Well, it's not exactly what I want, because the data comes already sorted from my PHP script on the server. – user1120146 Jul 16 '13 at 15:36
  • Solved it like this for now: `var orderedData = [ {'key':'3', 'value':'a'}, {'key':'2', 'value':'b'}, ... ];` isn't really nice but works. Just need to change my code about 100'000 times :-( – user1120146 Jul 16 '13 at 15:40