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

时间:2018-06-14 07:07:50

标签: javascript arrays typescript object

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

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



log.retention.hours




2 个答案:

答案 0 :(得分: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);




答案 1 :(得分:0)

要按yearmonth进行过滤,您只需要使用currentYear获取currentMonth,然后获取year和{{ 1}}迭代的month

这应该是你的代码:

date

<强>演示:

&#13;
&#13;
//Get the currentYear and the currentMonth
currentMonth = new Date().getMonth() + 1,
currentYear = new Date().getFullYear(),

//Get the year and month from the iterated date
var [year, month] = e.date.split('-');

//Then filter the dates
events = array.filter(e => {
    var [year, month] = e.date.split('-'); // Or, var month = e.date.split('-')[1];
    return (currentMonth === +month) && (currentYear == year);
});
&#13;
&#13;
&#13;