sort object properties and JSON.stringify

后端 未结 22 2327
南方客
南方客 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 don't understand why the complexity of the current best answers is needed, to get all the keys recursively. Unless perfect performance is needed, it seems to me that we can just call JSON.stringify() twice, the first time to get all the keys, and the second time, to really do the job. That way, all the recursion complexity is handled by stringify, and we know that it knows its stuff, and how to handle each object type :

    function JSONstringifyOrder( obj, space )
    {
        var allKeys = [];
        JSON.stringify( obj, function( key, value ){ allKeys.push( key ); return value; } )
        allKeys.sort();
        return JSON.stringify( obj, allKeys, space );
    }
    

提交回复
热议问题