Ordered JSONObject

后端 未结 3 630
有刺的猬
有刺的猬 2020-12-03 09:38

I have a servlet which talks with the database then returns a list of ordered (ORDER BY time) objects. At the servlet part, I have

                //access DB, r         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 10:10

    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..

提交回复
热议问题