Ordered JSONObject

As JSON objects do not inherently have an order, you should use an array within your JSON object to ensure order. As an example (based on your code):

 jsonObj = 
          { items:
            [ { name: "Stack", time: "..." },
              { name: "Overflow", time: "..." },
              { name: "Rocks", time: "..." },
              ... ] };

This structure will ensure that your objects are inserted in the proper sequence.

Based on the JSON you have above, you could place the objects into an array and then sort the array.

 var myArray = [];
 var resultArray;

 for (var j in jsonObj) {
   myArray.push(j);
 }

 myArray = $.sort(myArray, function(a, b) { return parseInt(a) > parseInt(b); });

 for (var i = 0; i < myArray.length; i++) {
   resultArray.push(jsonObj[myArray[i]]);
 }

 //resultArray is now the elements in your jsonObj, properly sorted;

But maybe that’s more complicated than you are looking for..

Leave a Comment