Luke G
Luke G

Reputation: 1747

Array ordering in javascript - different results comparing IE8 and Chrome

The array (note order of items):

{
  "5":{
      "Title":"Title A",
      "Desc":"Description A"
  },
  "15":{
      "Title":"Title B",
      "Desc":"Description B"
  },
  "10":{
      "Title":"Title C",
      "Desc":"Description C"
  },
  "1":{
      "Title":"Title D",
      "Desc":"Description D"
  },
  "20":{
      "Title":"Title E",
      "Desc":"Description E"
  }
}

Now, the js code below does change order if run on chrome or IE9.

for ( var i in data ) {
    alert(JSON.stringify(data[i]));
}

IE8 preserves original order, while newer browsers change the order to 1, 5, 10 ,15, 20.

Any idea why this may be happening? Is it possible to preserve original order in newer browsers?

Many thanks, Luke

Upvotes: 2

Views: 169

Answers (2)

Blender
Blender

Reputation: 298392

What you have there is not an array, but an object. Objects don't have any order. The browsers return keys in whatever order they want.

If you want some fixed order, put your objects into an array:

{
    "objects": [
        {
            "id": "5",
            "Title":"Title A",
            "Desc":"Description A"
        },
        {
            "id": "15",
            "Title":"Title B",
            "Desc":"Description B"
        },
        {
            "id": "10",
            "Title":"Title C",
            "Desc":"Description C"
        },
        {
            "id": "1",
            "Title":"Title D",
            "Desc":"Description D"
        },
        {
            "id": "20"
            "Title":"Title E",
            "Desc":"Description E"
        }
    }
}

Upvotes: 1

Pointy
Pointy

Reputation: 413826

What you've got there is not an array. It's just an object, and the order of presentation of properties is undefined.

edit — fun fact: the spec says that if an implementation decides to advertise some particular ordering in for ... in statements, then Object.keys() has to obey that same ordering rule. There need be no such rule, however. The spec doesn't go into much detail about how "undefined" an implementation can be, but for me a good rule-of-thumb is to code as if the order might be actively randomized :-)

Upvotes: 6

Related Questions