sort json object in javascript

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

    Here is a simple snippet that sorts a javascript representation of a Json.

    function isObject(v) {
        return '[object Object]' === Object.prototype.toString.call(v);
    };
    
    JSON.sort = function(o) {
    if (Array.isArray(o)) {
            return o.sort().map(JSON.sort);
        } else if (isObject(o)) {
            return Object
                .keys(o)
            .sort()
                .reduce(function(a, k) {
                    a[k] = JSON.sort(o[k]);
    
                    return a;
                }, {});
        }
    
        return o;
    }
    

    It can be used as follows:

    JSON.sort({
        c: {
            c3: null,
            c1: undefined,
            c2: [3, 2, 1, 0],
        },
        a: 0,
        b: 'Fun'
    });
    

    That will output:

    {
      a: 0,
      b: 'Fun',
      c: {
        c2: [3, 2, 1, 0],
        c3: null
      }
    }
    

提交回复
热议问题