如何过滤和订购Json数据

时间:2014-06-12 00:05:22

标签: javascript jquery json

我得到了关于ajax成功的json数据。

var videolist = [
  {
    "video_id": 0,
    "video_name": "Guerrero Beard",
    "timelength": 15
  },
  {
    "video_id": 1,
    "video_name": "Hallie Key",
    "timelength": 8
  },
  {
    "video_id": 2,
    "video_name": "Pitts Lloyd",
    "timelength": 27
  },
  {
    "video_id": 3,
    "video_name": "Corine Deleon",
    "timelength": 14
  }
]

我按时间长度过滤> 10,它的工作原理。

var result = [];
$.each(videolist, function(i, o){
    if(videolist[i].timelength >10)
        result.push(videolist[i]);
});

console.log(result);

但我也需要对它进行排序。我该如何对这个数组进行排序?

1 个答案:

答案 0 :(得分:0)

//filter
var result = videolist.filter(function(item) {
    return item.timelength > 10
}); 

//sort
var result = result.sort(function(a,b) { 
   return a.timelength - b.timelength
});

console.log(result);

你也可以按jquery过滤

var filterbyjquery = $.grep( videolist, function( n, i ) {
    return n.timelength > 10;
});

console.log(filterbyjquery);

fiddle