sort object properties and JSON.stringify

后端 未结 22 2325
南方客
南方客 2020-11-28 05:44

My application has a large array of objects, which I stringify and save them to the disk. Unfortunately, when the objects in the array are manipulated, and sometimes replac

22条回答
  •  生来不讨喜
    2020-11-28 06:12

    I took the answer from @Jason Parham and made some improvements

    function sortObject(obj, arraySorter) {
        if(typeof obj !== 'object')
            return obj
        if (Array.isArray(obj)) {
            if (arraySorter) {
                obj.sort(arraySorter);
            }
            for (var i = 0; i < obj.length; i++) {
                obj[i] = sortObject(obj[i], arraySorter);
            }
            return obj;
        }
        var temp = {};
        var keys = [];
        for(var key in obj)
            keys.push(key);
        keys.sort();
        for(var index in keys)
            temp[keys[index]] = sortObject(obj[keys[index]], arraySorter);       
        return temp;
    }
    

    This fixes the issue of arrays being converted to objects, and it also allows you to define how to sort arrays.

    Example:

    var data = { content: [{id: 3}, {id: 1}, {id: 2}] };
    sortObject(data, (i1, i2) => i1.id - i2.id)
    

    output:

    {content:[{id:1},{id:2},{id:3}]}
    

提交回复
热议问题