javascript - 根据 TypeScript 中的条件将数据从一个数组推送到另一个数组
问题描述
我想使用 TypeScript 将满足条件的所有数据从一个数组推送到另一个数组。
array: any =
[
{
Hostname: 'CBA',
Certificate_Expiry_Date: 'Thu Mar 25 16:32:48 GMT 2021',
'': ''
},
{
Hostname: 'CBCB',
Certificate_Expiry_Date: 'Wed Apr 07 11:19:01 IST 2021',
'': ''
},
{
Hostname: 'cbcb',
Certificate_Expiry_Date: 'Thu Apr 01 12:05:22 IST 2021',
'': ''
},
{
Hostname: 'cbm',
Certificate_Expiry_Date: 'Sat Apr 04 10:45:19 IST 2020',
];
alert() {
if (this.array.Certificate_Expiry_Date > Date) {
this.array.forEach(item => {
this.alertsArray.push(
item.Hostname,
item.Certificate_Expiry_Date
);
});
}
console.log(this.alertsArray);
}
我希望上面的代码在证书到期日期不到 2 个月时将对象推送到警报数组中,但是当我以这种方式尝试时,它不起作用,感谢您提供任何帮助
解决方案
看来您正在尝试使用点表示法访问数组上的未定义值 - 这在数组上不可用
alert() {
if (this.array.Certificate_Expiry_Date > Date) { <--- dot notation on the array wont work
this.array.forEach(item => {
this.alertsArray.push(
item.Hostname,
item.Certificate_Expiry_Date
);
});
}
console.log(this.alertsArray);
}
尝试通过数组循环 - 检查您的日期是否相隔不到 60 天 - 如果是,则将该项目推入您的警报数组
通过将过期时间和今天转换为转换为毫秒的新 Date() 对象来检查您的状况,然后将差值除以一天中的毫秒数,看看是否小于 60 天。
您可能需要在这里调整数学以使其工作
alert() {
const milsInDay = (1000*60*60*24);
const today = new Date().getTime() / milsInDay;
this.array.forEach((item) => {
const exp = new Date(item.Certificate_Expiry_Date).getTime() / milsInDay;
if(exp - today < 60) {
this.alertsArray.push(item);
}
});
console.log(this.alertsArray);
}
推荐阅读
- python - Django 正在向我发送一封关于“无效 HTTP_HOST 标头”的电子邮件
- matlab - mex编译代码语句中如何使用变量?
- laravel - Laravel RESTAPI,显示来自服务器端的调试
- python - 以前未见过的 Web 元素参考
- javascript - 通过 Javascript 更改范围滑块背景
- python - 为什么 event.type 函数返回名称错误?
- ios - Swift 编译错误 - 无法构建 Objective-C 模块“RxAlamofire”
- jupyter-notebook - 类型对象“KMeans”没有属性“labels_”
- javascript - 如何在良好的实践中中断所有承诺
- python - 如何确保对函数的递归调用是我认为的那样?