无法获取具有相同月份和年份的记录

时间:2019-02-13 10:01:38

标签: javascript momentjs

我有一个对象列表,其属性名为created

let objs = [
   { id: "1", created: "2019-02-12 00:00:00" },
   { id: "2", created: "2018-02-12 00:00:00" },
   { id: "3", created: "2017-02-12 00:00:00" },
   { id: "4", created: "2016-02-12 00:00:00" },
   { id: "5", created: "2015-02-12 00:00:00" }
]

我想返回所有截至2019年和月份为02的记录,所以我做了:

var curr_date = moment(moment(), "YYYY-MM-DD");
var in_month = objs.filter((item) => function () {
        return (moment(item.created, format).month() == curr_date.month() && 
                    moment(item.created, format).year() == curr_date.year())
});

问题是in_month总是返回整个数组,为什么?预期的输出应该是ID为1的记录

4 个答案:

答案 0 :(得分:5)

仅对其进行了一点修复,问题是您的过滤器函数评估了您传递的function()而不是执行它,将其删除是可行的:

let objs = [
   { id: "1", created: "2019-02-12 00:00:00" },
   { id: "2", created: "2018-02-12 00:00:00" },
   { id: "3", created: "2017-02-12 00:00:00" },
   { id: "4", created: "2016-02-12 00:00:00" },
   { id: "5", created: "2015-02-12 00:00:00" }
]

let format = "YYYY-MM-DD"
var curr_date = moment(moment(), format);
var in_month = objs.filter(item => 
  moment(item.created, format).month() == curr_date.month() && 
  moment(item.created, format).year() == curr_date.year()
 );

console.log(in_month)

答案 1 :(得分:1)

已经回答了,但是仍然需要一些修复,例如创建多个矩对象,而不是只执行一次。

let objs = [
	{ id: "1", created: "2019-02-12 00:00:00" },
	{ id: "2", created: "2018-02-12 00:00:00" },
	{ id: "3", created: "2017-02-12 00:00:00" },
	{ id: "4", created: "2016-02-12 00:00:00" },
	{ id: "5", created: "2015-02-12 00:00:00" }
]

var curr_date = moment(moment(), "YYYY-MM-DD");
var in_month = objs.filter(({ created }) => {
	let date = moment(created, "YYYY-MM-DD");
	return date.month() == curr_date.month() && date.year() == curr_date.year();
});
console.log(in_month)

答案 2 :(得分:0)

你在这里

var in_month = objs.filter(item => 
  moment(item.created).format('YYYY') === '2019' &&
  moment(item.created).format('MM') === '02'
);

当您console.log(in_month)时,您会得到结果:)

,并且数组中日期的正确格式是YYYY-MM-DD HH:mm:ss

答案 3 :(得分:0)

这是一个可行的示例。

我没有过滤集合,而是将匹配元素的ID添加到数组中。
将ID保存到对象中,我们以后可以再次使用相同的集合(让objs)。

let objs = [
   { id: "1", created: "2019-02-12 00:00:00" },
   { id: "2", created: "2018-02-12 00:00:00" },
   { id: "3", created: "2017-02-12 00:00:00" },
   { id: "4", created: "2016-02-12 00:00:00" },
   { id: "5", created: "2015-02-12 00:00:00" }
]

var now = moment();
var targetYear = now.year();
var targetMonth = now.month(); //0 index

var hits = [];

objs.forEach(function (e) {
  var created = moment(e.created, "YYYY-MM-DD");
  if (created.year() == targetYear &&
  created.month() == targetMonth) {
    hits.push(e.id);
  }
});

console.log(hits);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>