如何使用jQuery.grep()过滤多维JSON对象

时间:2011-09-21 08:02:32

标签: javascript jquery json

我有一个JSON对象,如下所示:

{"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"
}

1 个答案:

答案 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
});