Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a Multi-dimension JSON object with jQuery.grep()

I have a JSON object that goes like this:

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

I would like to filter the JSON object to obtain data of those taller than 170 and heavier than 70 and subsequently sort this object. From the jQuery website, I understand that filtering would be easily achieved on a linear array with something like:

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

How do I filter both weight and height concurrently to get this:

{"data":
 [
  {"name":"Ben","height":"182","weight":"90"},
 ]
 ,"school":"Dover Secondary"
}
like image 830
Question Overflow Avatar asked Sep 21 '11 08:09

Question Overflow


1 Answers

I think you mean this: 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
});
like image 145
pimvdb Avatar answered Sep 22 '22 13:09

pimvdb