Skip to content Skip to sidebar Skip to footer

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 ove

Solution 1:

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.

Solution 2:

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 purposesfunctionaddPages(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:

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

Solution 3:

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']]

Solution 4:

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.

Post a Comment for "Iterate Over Jquery Json Object In Original Order"