sort object properties and JSON.stringify

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

    I made a function to sort object, and with callback .. which actually create a new object

    function sortObj( obj , callback ) {
    
        var r = [] ;
    
        for ( var i in obj ){
            if ( obj.hasOwnProperty( i ) ) {
                 r.push( { key: i , value : obj[i] } );
            }
        }
    
        return r.sort( callback ).reduce( function( obj , n ){
            obj[ n.key ] = n.value ;
            return obj;
        },{});
    }
    

    and call it with object .

    var obj = {
        name : "anu",
        os : "windows",
        value : 'msio',
    };
    
    var result = sortObj( obj , function( a, b ){
        return a.key < b.key  ;    
    });
    
    JSON.stringify( result )
    

    which prints {"value":"msio","os":"windows","name":"anu"} , and for sorting with value .

    var result = sortObj( obj , function( a, b ){
        return a.value < b.value  ;    
    });
    
    JSON.stringify( result )
    

    which prints {"os":"windows","value":"msio","name":"anu"}

提交回复
热议问题