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"

1
  • 2
    Object keys are un-ordered in JavaScript. This is in the language specification, under the for... in loop that jQuery's .each uses. If you want an ordered collection use an array Commented Aug 10, 2013 at 21:13

3 Answers 3

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.

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

Comments

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.

Comments

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/

1 Comment

This is a totally underrated answer. This one worked great for me, thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.