sort object properties and JSON.stringify

后端 未结 22 2321
南方客
南方客 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:20

    A recursive and simplified answer:

    function sortObject(obj) {
        if(typeof obj !== 'object')
            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]]);       
        return temp;
    }
    
    var str = JSON.stringify(sortObject(obj), undefined, 4);
    

提交回复
热议问题