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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With