Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over jQuery JSON object in original order

I've got some json data in a map object which is sorted by time. The key is an integer id and the value is an object which contains a timestamp. However when I try to iterate over this data with the jQuery $.each function, the results come back sorted by the key instead. How can I iterate over my collection of objects in their original order?

Code example:

$.getJSON(url, addPages);
function addPages(pageData) {
    $.each(pageData, function(key,value){
        alert(key+' : '+value);
    }
}
like image 457
Doug Avatar asked Feb 01 '11 00:02

Doug


1 Answers

Objects are un-ordered sets. You can't specify an order on them in a cross-browser complaint manner. There is no concept of original order unless it's already ordered by a rule.

So sort the data on the server and then enumerate over it in the same sorted order.

Alternatively format the JSON to be

{ "values": [
   { "someKey": "someVal" },
   { "someOtherKey": "someOtherVal" }
] }

You can iterate over the array with a for (i = 0; i < len; i++) loop and "garantuee" the original order.

like image 130
Raynos Avatar answered Oct 17 '22 08:10

Raynos