sort json object in javascript

后端 未结 4 1230
感情败类
感情败类 2020-11-28 05:05

For example with have this code:

var json = {
    \"user1\" : {
        \"id\" : 3
    },
    \"user2\" : {
        \"id\" : 6
    },
    \"user3\" : {
              


        
4条回答
  •  借酒劲吻你
    2020-11-28 05:59

    In some ways, your question seems very legitimate, but I still might label it an XY problem. I'm guessing the end result is that you want to display the sorted values in some way? As Bergi said in the comments, you can never quite rely on Javascript objects ( {i_am: "an_object"} ) to show their properties in any particular order.

    For the displaying order, I might suggest you take each key of the object (ie, i_am) and sort them into an ordered array. Then, use that array when retrieving elements of your object to display. Pseudocode:

    var keys = [...]
    var sortedKeys = [...]
    for (var i = 0; i < sortedKeys.length; i++) {
      var key = sortedKeys[i];
      addObjectToTable(json[key]);
    }
    

提交回复
热议问题