首页 > 解决方案 > 根据 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 个月时将对象推送到警报数组中,但是当我以这种方式尝试时,它不起作用,感谢您提供任何帮助

标签: javascriptangulartypescript

解决方案


看来您正在尝试使用点表示法访问数组上的未定义值 - 这在数组上不可用

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

推荐阅读