繁体   English   中英

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

[英]How to get last object from array of object based on condition in angular 8

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

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

主页.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);


  }

}

您可以编写一个快速函数来更新值,如下所示

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

工作示例: Stackblitz

闪电战 GIF

工作 gif

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM