1

I have an object which would translate into a Dictionary in C# and I'm trying to loop through all my "keys" so that I can draw my objects in order.

Let's say that this dictionary contains three objects with the keys 1, 2 and 3.

for (var key in myDictionary) {
    if (key === "indexOf" || key === "length")
        continue;
    // Do stuff...
}

Now, in IE9+, Chrome and Firefox, the output will be 1, 2, 3 while in IE8 the output is 2, 1, 3. As it is crucial for my application that these objects are given in order you can understand that this is unwanted behavior.

My question, therefore, is: Why does this happen and is there a known workaround that fixes my issue?

Erik Karlstrand
  • 1,360
  • 7
  • 19

1 Answers1

2

That happens because the properties in an object doesn't have any specific order. The order that you get the propeties is depending on the implementation, i.e. how the properties are stored internally in the object.

The browsers that return the properties in a different order than you expect aren't doing anything wrong, the actual error is to expect any specific order.

If you want the properties in a specific order, you need to sort them. You can put them in an array, sort the array, and loop through the array.

Guffa
  • 640,220
  • 96
  • 678
  • 956