如何根据角度8中的条件从对象数组中获取最后一个对象

我有一些对象,我使用settimeout函数接收一个又一个对象,然后每次将其推入数组以填充到表中。这是在我的项目中动态出现的,但仅供参考,我settimeout在这里使用和硬编码。


现在我的问题是,每当我使用 接收数据时settimeout,我需要通过使用vehicle_number 进行过滤来获取最后一个对象(如果它包含相同的vehicle_number,我需要获取该vehicle_number 的最后一个对象),并且需要再次填充/推入表中。这是我尝试过的代码。


home.component.html

<div>

<table>

<tr *ngFor="let x of groupList">

<td>{{x.vehicle_number}}</td>

<td>{{x.status}}</td>

</tr>

</table>

</div>

home.component.ts

import { Component, OnInit } from '@angular/core';



@Component({

  selector: 'app-home',

  templateUrl: './home.component.html',

  styleUrls: ['./home.component.css']

})


export class HomeComponent implements OnInit {

imageSource :any;

statusdata1: any;

vehicle_number:any;

groupList:any = [];


constructor() {}

  ngOnInit() {

     /* First data */

    this.statusdata1 = {"vehicle_number":1,"status":"red"};

     this.groupList.push(this.statusdata1);

     console.log(this.groupList);


     /* second data */

    setTimeout (() => {

        this.statusdata1 = {"vehicle_number":1,"status":"green"};

         this.groupList.push(this.statusdata1);


         console.log(this.groupList);

      }, 5000);

   /* Third data */


      setTimeout (() => {

        this.statusdata1 = {"vehicle_number":2,"status":"yellow"};

         this.groupList.push(this.statusdata1);

         console.log(this.groupList);

      }, 10000);



  }


}


智慧大石
浏览 44回答 1
1回答

白衣非少年

您可以编写一个快速函数来更新值,如下所示private updateGroupList(statusData: any) {  for (const key in this.groupList) {    if (this.groupList[key].vehicle_number === statusData.vehicle_number) {      this.groupList[key].status = statusData.status;      return;    }  }  this.groupList.push(statusData);}您可以将this.groupList.push()中的所有ngOnInit()内容替换为this.updateGroupList(this.statusdata1).ngOnInit() {  /* First data */  this.statusdata1 = {"vehicle_number":1,"status":"red"};  this.updateGroupList(this.statusdata1);  console.log(this.groupList);  /* Second data */  setTimeout (() => {    this.statusdata1 = {"vehicle_number":1,"status":"green"};    this.updateGroupList(this.statusdata1);    console.log(this.groupList);  }, 5000);  /* Third data */  setTimeout (() => {    this.statusdata1 = {"vehicle_number":2,"status":"yellow"};    this.updateGroupList(this.statusdata1);    console.log(this.groupList);  }, 10000);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5