2

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

3
  • 7
    That's not an array. That's an object. Objects don't have an order. Commented Jan 2, 2013 at 17:37
  • 1
    +1 for the example. I've always wanted to see a proof that property order is not preserved in objects. Commented Jan 2, 2013 at 17:40
  • For those wondering, JavaScript objects are basically implemented as dictionaries/hash tables. Hence, the undefined ordering. Commented Jan 2, 2013 at 17:41

2 Answers 2

6

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 :-)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.