sort json object in javascript

后端 未结 4 1226
感情败类
感情败类 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:35

    First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.

    Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.

    One option might be to make your data look like this:

    var json = [{
        "name": "user1",
        "id": 3
    }, {
        "name": "user2",
        "id": 6
    }, {
        "name": "user3",
        "id": 1
    }];
    

    Now you have an array of objects, and we can sort it.

    json.sort(function(a, b){
        return a.id - b.id;
    });
    

    The resulting array will look like:

    [{
        "name": "user3",
        "id" : 1
    }, {
        "name": "user1",
        "id" : 3
    }, {
        "name": "user2",
        "id" : 6
    }];
    

提交回复
热议问题