Javascript 如何使用 jQuery.grep() 过滤多维 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7496439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to filter a Multi-dimension JSON object with jQuery.grep()
提问by Question Overflow
I have a JSON object that goes like this:
我有一个像这样的 JSON 对象:
{"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:
我想过滤 JSON 对象以获取那些高于 170 和重于 70 的数据,然后对该对象进行排序。从jQuery 网站,我了解到可以在线性数组上轻松实现过滤,例如:
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"
}
回答by pimvdb
I think you mean this: http://jsfiddle.net/NRuM7/1/.
我想你的意思是: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
});