对json按某个键的值进行排序

  1. /**  
  2.  * Created with PyCharm.  
  3.  * User: jennyzhang  
  4.  * Date: 16-12-7  
  5.  * Time: 下午3:33  
  6.  * To change this template use File | Settings | File Templates.  
  7.  */  
  8.   
  9. $(document).ready(function () {  
  10.     //对json进行降序排序函数  
  11.     var colId="age"  
  12.     var desc = function(x,y)  
  13.     {  
  14.         return (x[colId] < y[colId]) ? 1 : -1  
  15.     }  
  16.     //对json进行升序排序函数  
  17.     var asc = function(x,y)  
  18.     {  
  19.         return (x[colId] > y[colId]) ? 1 : -1  
  20.     }  
  21.     var arr2 = [  
  22.         {name:"kitty", age:12},  
  23.         {name:"sonny", age:9},  
  24.         {name:"jake", age:13},  
  25.         {name:"fun", age:24}  
  26.     ];  
  27.     document.writeln("按age进行升序排序:<br>");  
  28.     arr2.sort(asc); //升序排序  
  29.     document.writeln(JSON.stringify(arr2));  
  30.   
  31.   
  32.     document.writeln("<br>按age进行降序排序:<br>");  
  33.     arr2.sort(desc); //降序排序  
  34.     document.writeln(JSON.stringify(arr2));  
  35.   
  36. });  

猜你喜欢

转载自blog.csdn.net/yelin042/article/details/80780044
今日推荐