开发者

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 o开发者_运维百科bjects 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.


You could copy the key value pairs into an array of objects and then use Array.sort to put them in order.

// $.getJSON(url, addPages); //removed for test purposes
function addPages(pageData) {
    var pageItems = [];
    $.each(pageData, function(key,value){
        pageItems.push( { key: key, value: value } );
    });
    // Assuming you can do arithmetic on timestamps
    pageItems.sort( function(a,b){ return a.value.timeStamp - b.value.timeStamp; } ); 
    $.each(pageItems, function(index,pageItem){
        alert(pageItem.key+' : '+pageItem.value.timeStamp);
    });
}

My test script:

var testData = { 
  '12': { timeStamp: 55 },
  '16': { timeStamp: 655 },
  '123': { timeStamp: 455 },
  '312': { timeStamp: 955 },
  '132': { timeStamp: 255 },
  '126': { timeStamp: 455 },
  '162': { timeStamp: 355 }
  };
addPages(testData);


In firefox objects keep the order.. in chrome they don't. No idea about other browser but two different implementations already show that you cannot rely on it.

If you need something ordered, use a list; if you need something with both non-numeric keys and a certain order, the easiest way would be using a list of [key, value] lists:

[['abd', 'def'], ['ghi', 'jkl']]


If by "original" you mean the timestamp in the object, I don't think there's any foolproof option other than to first explicitly sort the array, and only then loop through it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜