javascript 按字段对json进行排序

 1 Array.prototype.sortObjectWith = function ( key, t, fix){
 2     if( !this.length ){ return this;}          // 空数组
 3     t = t ==='desc'? 'desc': 'asc';    // ascending or descending sorting, 默认 升序
 4     fix = Object.prototype.toString.apply( fix )==='[object Function]'? fix: function(key){ return key; };
 5     switch( Object.prototype.toString.apply( fix.call({},this[0][key]) ) ){
 6         case '[object Number]':
 7             return this.sort( function(a, b){ return t==='asc'?( fix.call({},a[key]) - fix.call({},b[key]) ) :( fix.call({},b[key]) - fix.call({},a[key])); } );
 8         case '[object String]':
 9             return this.sort( function(a, b){ return t==='asc'? fix.call({},a[key]).localeCompare( fix.call({},b[key])) : fix.call({},b[key]).localeCompare( fix.call({},a[key])); } );
10         default: return this;  // 关键字不是数字也不是字符串, 无法排序
11     }
12 }

使用方法:

json.sortObjectWith("id","desc","fix");