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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:26:17  来源:igfitidea点击:

Filter an array based on an object property

javascript

提问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:.

用户Array.prototype.filter()如下:

var filteredEvents = events.filter(function(event){
    return event.date == '22-02-2016';
});