1

I've created an object that I'm trying to loop through, but the .each() function is trying to first sort the object and then loop through it, giving undesirable results. I'm using Chrome, btw, and I've heard object looping can be fairly browser-dependent.

The object:

var myObject = {"000": "12:00", "100": "1:00", "200": "2:00" .. and so on }

I loop through the object with the each function

$.each(myObject, function (key, value) {
    // display value 
} // outputs 1:00 2:00 12:00

I want it the output to be 12:00 1:00 2:00, the order in which I provided for the object. I don't have much leeway in changing the object keys, so I'd like to keep those if I can.

Here's the JSFiddle: http://jsfiddle.net/hyc8U/

Thanks!

PS. I'm not sure if this behavior of .each() is technically "in order" or "out of order"

Alper
  • 107
  • 1
  • 2
  • 8
  • 2
    Object keys are un-ordered in JavaScript. This is in the language specification, [under the `for... in` loop](http://es5.github.io/#x12.6.4) that jQuery's .each uses. If you want an ordered collection use an array – Benjamin Gruenbaum Aug 10 '13 at 21:13

3 Answers3

6

Properites of a javascript object are not ordered. You lose all the information of the order which they were provided.

If you want a specific order, you can use an array, or fetch the keys of the object and sort them by a user-defined function.

Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
3

Object keys are unordered in Javascript. You will need to convert your object into an array that looks like this:

    var myList = [{key: "000": val: "12:00"}, 
                  {key: "100": val: "1:00"}, 
                  {key: "200": val: "2:00"}, 
                  // ...
                 ];

Then you can sort the array (myList.sort(function(o) {return o.key;});), and call .each on the sorted array.

Joshua D. Boyd
  • 4,808
  • 3
  • 29
  • 44
2

It looks like the insertion order is not arbitrary or is that just an accident? Otherwise you could just get keys and sort them and access the object in the sorted key array order:

var myObject = {"000": "12:00", "100": "1:00", "200": "2:00"};
$.each(Object.keys(myObject).sort(), function(i, v){
    $("div").append(myObject[v] + "<br>");
});

http://jsfiddle.net/hyc8U/2/

Esailija
  • 138,174
  • 23
  • 272
  • 326