Javascript 根据对象属性过滤数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35231008/
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
Filter an array based on an object property
提问by Miguel Moura
I have an array of objects, something as follows:
我有一个对象数组,如下所示:
var events = [
{ date: "18-02-2016", name: "event A" },
{ date: "22-02-2016", name: "event B" },
{ date: "19-02-2016", name: "event C" },
{ date: "22-02-2016", name: "event D" }
];
And I have a date, for example "22-02-2016". How can I get an array with all object which date is the same as the given date? So in this example I would get events B and D.
我有一个日期,例如“22-02-2016”。如何获取包含所有对象的数组,其日期与给定日期相同?所以在这个例子中,我会得到事件 B 和 D。
回答by newfurniturey
You could use array's filter()
function:
您可以使用数组的filter()
功能:
function filter_dates(event) {
return event.date == "22-02-2016";
}
var filtered = events.filter(filter_dates);
The filter_dates()
method can be standalone as in this example to be reused, or it could be inlined as an anonymous method - totally your choice =]
该filter_dates()
方法可以像本示例中那样独立进行重用,也可以作为匿名方法内联 - 完全由您选择 =]
A quick / easy alternative is just a straightforward loop:
一个快速/简单的替代方案只是一个简单的循环:
var filtered = [];
for (var i = 0; i < events.length; i++) {
if (events[i].date == "22-02-2016") {
filtered.push(events[i]);
}
}
回答by leo.fcx
User Array.prototype.filter()as follows:.
var filteredEvents = events.filter(function(event){
return event.date == '22-02-2016';
});