2014-06-12 147 views
0

我得到了像這樣的Ajax成功的json數據。如何過濾和訂購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 
    } 
] 

而且我通過timelength> 10過濾它,它工作。

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

console.log(result); 

但我也需要對它進行排序。我怎樣才能排序這個數組?

回答

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

+0

過濾不幸的是'過濾器()'方法將無法在IE瀏覽器IE9之前的工作。 – hutchbat