我想根据当前月份和年份显示对象
这会根据月份筛选对象,我还需要根据年份筛选对象。
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);
最佳答案
要按year
和month
过滤,您只需要获取currentYear
和currentMonth
,然后获取迭代的 date
的 year
和 month
。
你的代码应该是这样的:
//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/