2011-09-21 82 views
10

我有一個是這樣的一個JSON對象多維JSON對象:如何篩選與jQuery.grep()

{"data": 
[ 
    {"name":"Alan","height":"171","weight":"66"}, 
    {"name":"Ben","height":"182","weight":"90"}, 
    {"name":"Chris","height":"163","weight":"71"} 
] 
,"school":"Dover Secondary" 
} 

我想過濾的JSON對象獲得比那些更高的數據170並且重於70,然後對這個物體進行分類。從jQuery website,據我所知,過濾會很容易的線性陣列上的東西,如實現:

arr = jQuery.grep(arr, function(element, index){ 
    return (element > 70 && index = 'weight'); 
}); 

如何過濾重量和高度同時得到這個:

{"data": 
[ 
    {"name":"Ben","height":"182","weight":"90"}, 
] 
,"school":"Dover Secondary" 
} 
+0

這不是我真正的體重和身高! –

回答

21

我想你這意味着:http://jsfiddle.net/NRuM7/1/

var obj = {"data": 
[ 
    {"name":"Alan","height":"171","weight":"66"}, 
    {"name":"Ben","height":"182","weight":"90"}, 
    {"name":"Chris","height":"163","weight":"71"} 
] 
,"school":"Dover Secondary" 
}; 

obj.data = jQuery.grep(obj.data, function(element, index){ 
    return element.weight > 70 && element.height > 170; // retain appropriate elements 
}); 
+0

錯誤..我想過濾重量和身高。可以做到嗎? –

+0

@Ben:對不起,請參閱我的編輯。 – pimvdb

+0

是的,你是對的。謝謝 ;) –