根据月份和年份过滤对象数组

Moh*_*hir 5 javascript arrays object typescript

我想根据当前月份和年份显示对象

这将根据月份过滤对象,我也需要根据年份过滤对象。

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-06-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);
Run Code Online (Sandbox Code Playgroud)

Ank*_*wal 0

您可以创建年和月的字符串表示形式2018-06,并将该值作为属性中的子字符串进行检查date,以过滤掉当年和当月的记录。

var array = [{
    title: "a",
    date: "2018-03-29"
  }, {
    title: "b",
    date: "2018-04-13"
  }, {
    title: "c",
    date: "2018-04-12"
  }, {
    title: "leave",
    date: "2018-06-11"
  }, {
    title: "d",
    date: "2018-04-16"
  },
   {
    title: "e",
    date: "2018-06-18"
  }],
  currentMonth = '0'+(new Date().getMonth() + 1),
  currentYear = new Date().getFullYear()
  events = array.filter((e) => {
    var dateStr = currentYear+'-'+currentMonth;
    return (e.date.indexOf(dateStr) !== -1)
  });
console.log(events);
Run Code Online (Sandbox Code Playgroud)