javascript 从列表中选择满足条件的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16613425/
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
Select Objects from List where they meet a condition
提问by Jason
Let's say I have the following javascript object containing three objects:
假设我有以下包含三个对象的 javascript 对象:
var list = [
{ age: 5 },
{ age: 10 },
{ age: 15 }
];
Is there a way of selecting a subset of elements based on age using JavaScript and JQuery? For example:
有没有办法使用 JavaScript 和 JQuery 根据年龄选择元素子集?例如:
$.select(list, element.age>=10);
$.select(list, element.age>=10);
回答by Bergi
Is there a way of selecting a subset of elements based on age…
有没有办法根据年龄选择元素子集……
Yes.
是的。
…using JavaScript…
……使用 JavaScript……
list.filter(function(element){ return element.age >= 10; })
…and jQuery
...和 jQuery
$.grep(list, function(element){ return element.age >= 10; })
回答by Andrew Whitaker
First of all, that's not JSON, it's an array literal filled with object literals.
首先,这不是 JSON,它是一个填充了对象字面量的数组字面量。
$.grep
is handy here:
$.grep
在这里很方便:
var filtered = $.grep(list, function (el) {
return el.age >= 10;
});
Example:http://jsfiddle.net/ytmhR/