0

I used following code to add element in JSON

jobs[job.id] = jobObject

job ids are returned in 110,81,195,126,112 sequence

but when i check final JSON with alert(JSON.stringify(jobs)) it gives me output like

{"81":{"439":"none"},"110":{"386":0,"407":";^1^1^1^1^1"},"112":{},"126":{"440":"none"},"195":{"14":"20","400":"0"}}

which is sorted by id

why is it returned sorted and how can I get final JSON with same order ids are returned

Vikram
  • 3,171
  • 7
  • 37
  • 67
  • 1
    JSON is unpredictable and mostly gets out sorted alphabetically/numerically. It's not meant to *keep order* but to preserve *property-values* pairs. What you're looking for is an Array. – Roko C. Buljan May 11 '15 at 10:49
  • 2
    downvote ? Someone forgot to mention reason may be it could help me improve my question :-/ – Vikram May 11 '15 at 10:53
  • 2
    Just to share with you a nice tip on how to explore your object: don't use `alert()` !! Hit **F12** an open **console**. In your code use: `console.dir( jobs );`. There you go- have fun. – Roko C. Buljan May 11 '15 at 10:58

1 Answers1

3

JavaScript objects are not ordered. You are not guaranteed order when you insert items into an object or when you take them out.

If you want an ordered list, use an array of objects.

[{"81": {"439": "none"},
 {"110": ....,
 ...
]
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • I want it like `{"110":{"386":0,"407":";^1^1^1^1^1"},"81":{"439":"none"},"195":{"14":"20","400":"0"},"126":{"440":"none"},"112":{}}` – Vikram May 11 '15 at 11:02
  • I realize that. You can't. JavaScript objects do not have a defined order. – Madara's Ghost May 11 '15 at 11:02
  • it is in same order as job ids are returned – Vikram May 11 '15 at 11:02
  • so there should be a method to reorder them as per my requirement after getting final `JSON` ? – Vikram May 11 '15 at 11:04
  • 1
    JavaScript objects **do not have order**, you can't order anything that is **explicitly specified to not have order**. If you want order, use arrays. Otherwise, deal with the fact that objects ***don't have any order***. – Madara's Ghost May 11 '15 at 11:05