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

标签 javascript arrays typescript object

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

这会根据月份筛选对象,我还需要根据年份筛选对象。

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);

最佳答案

要按yearmonth 过滤,您只需要获取currentYearcurrentMonth,然后获取迭代的 dateyearmonth

你的代码应该是这样的:

//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);
});

演示:

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,
  currentYear = new Date().getFullYear(),
  events = array.filter(e => {
    var [year, month] = e.date.split('-'); // Or, var month = e.date.split('-')[1];
    return (currentMonth === +month) && (currentYear == year);
  });
console.log(events);

关于javascript - 根据月份和年份过滤对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50851537/

相关文章:

javascript - 如何在 Vue 中使过滤列表更具动态性

javascript - 数组长度与数组中值的数量

php - PHP-从数组中获取字段并将其转换为数组

angular - 如何使用 Angular 2 组件中的路由器打开新的浏览器选项卡?

javascript - 在 xpath 搜索中使用通配符

javascript - 根据值在两个对象数组之间进行过滤

javascript - 在 html 数据属性中存储图像标签数组并在单击时检索它们

javascript - 如何更改 jquery.mentionsInput(jquery 插件)中的默认选项?

javascript - 如何合并包含符号的javascript对象?

typescript - 如何使用类型保护解析接口(interface)的 typescript 联合类型