【问题标题】:fiter array of objects based on date property根据日期属性过滤对象数组
【发布时间】:2018-09-27 09:19:03
【问题描述】:

我想根据当前月份显示对象 我的代码是

 for (let m of  this.monthEvent){
     m=new Date();            
         if(m.getMonth() === new Date().getMonth()){
           this.thisMonth=m;
   }
     return this.thisMonth;

我的数组是

[{title: "", date: "2018-03-29"},
 {title: "", date: "2018-04-13"},
 {title: "", date: "2018-04-12"},
 {title: "leave", date: "2018-04-11"}
 {title: "", date: "2018-04-16"}]

它表明 m.getTime 不是一个函数

我想显示当前月份的事件

提前致谢

【问题讨论】:

  • myArray.filter(event => event.date.indexOf('currentMonth') > -1)尝试自己解决日期解析;)

标签: javascript arrays date ionic-framework ionic2


【解决方案1】:
  • 您可以使用filter函数获取具体事件。
  • 使用解构赋值var [_, month] = e.date.split('-');获取事件月份

var array = [{    title: "a",    date: "2018-03-29"  },  {    title: "b",    date: "2018-04-13"  },  {    title: "c",    date: "2018-04-12"  },  {    title: "leave",    date: "2018-04-11"  },  {    title: "d",    date: "2018-04-16"  }],
    currentMonth = new Date().getMonth() + 1,
    events = array.filter(e => {
        var [_, month] = e.date.split('-'); // Or, var month = e.date.split('-')[1];
        return currentMonth === +month;
    });

console.log(events);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 你能解释一下 [_, month] = e.date.split('-') over e.date.split('-')[1]; 的用途吗?谢谢
  • @MohammedAbdulkadhir 该行获取"2018-03-29" 的月份,使用函数split 我们得到如下内容["2018", "03", "29"],索引1 包含月份。
  • 嗨Ele还有一件事如何根据当前月份和年份过滤对象
猜你喜欢
  • 2018-12-25
  • 2018-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 2021-04-15
  • 2017-03-19
相关资源
最近更新 更多