1

I have an array returned by a JSON function looks like that :

{"178":"05HY24","179":"1HY12","292":"1HY24","180":"3HY12"}

I am using the function each to put elements to a select list :

$.each(value, function(k, v) {
                select += '<option value="'+ k +'">'+ v +'</option>'
            }

The each function is not executed in the order of the array because the element with id 292 is always at the end of my list. And when I debug in the each function the last value launched is the element 292. How can I do to make a list by keeping the order of the array?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Etienne
  • 408
  • 2
  • 9
  • 28

1 Answers1

0

"An object is an unordered set of name/value pairs"

JSON key/values are not ordered, so you can't assume anything about them being sorted in anyway.

if you need to process the values in a certain order you'd need to sort them/ cast them to a object/array before hand

atmd
  • 7,430
  • 2
  • 33
  • 64
  • Well... I don't know what you pasted but this is outdated. – Denys Séguret Jul 07 '15 at 15:11
  • 1
    [it's from the json spec](http://www.json.org/), can you explain why/how it's outdated? – atmd Jul 07 '15 at 15:12
  • which doesn't really matter here. What matters is what really happens (in JS) and how it is specified: http://stackoverflow.com/questions/30076219/does-es6-introduce-a-well-defined-order-of-enumeration-for-object-properties – Denys Séguret Jul 07 '15 at 15:13
  • but that's refereing to a javascript object, not json, they are not the same thing – atmd Jul 07 '15 at 15:15
  • What you must get is that it specifies how JSON is parsed (in JS). The old JSON spec wasn't considered as satisfying, so it was circumvented by ES, sort of. That's now how it works. BTW the spec only formalized what was already done by JS engines. – Denys Séguret Jul 07 '15 at 15:15