除了偶尔的jQuery选择器和元素修改之外,我在javascript上也不是很好。对于我遇到的问题,我需要按日期过滤掉一个javascript对象。我的结构看起来像这样:
Object { version: "3.1.1", released_on: "2016-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 }
我希望在"2016-08-21T00:00:00.000Z"
和"2010-08-21T00:00:00.000Z"
之间找到10年以来的所有对象。我遇到的问题是released_on:
字段是字符串而不是日期。我是否需要创建一个new Date()
对象将其转换为字符串,然后使用.filter
或者我会相反,将字符串转换为日期然后过滤。有人曾尝试过这样的事吗?
答案 0 :(得分:3)
您可以执行以下操作;
var data = [{ version: "3.1.1", released_on: "2016-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 },
{ version: "3.1.1", released_on: "2011-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 },
{ version: "3.1.1", released_on: "2009-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 },
{ version: "3.1.1", released_on: "2006-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 },
{ version: "3.1.1", released_on: "2013-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 },
{ version: "3.1.1", released_on: "2017-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 },
{ version: "3.1.1", released_on: "2015-08-21T00:00:00.000Z", high_vulns: 15, medium_vulns: 10, low_vulns: 5 },
],
ed = new Date("2016-08-21T00:00:00.000Z").getTime(),
sd = new Date("2010-08-21T00:00:00.000Z").getTime(),
result = data.filter(d => {var time = new Date(d.released_on).getTime();
return (sd < time && time < ed);
});
console.log(result);