为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

智慧大石 2023-10-04 14:22:33
我有一些对象,我使用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.tsimport { 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);  }}
查看完整描述

1 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞

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


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

}

查看完整回答
反对 回复 2023-10-04
  • 1 回答
  • 0 关注
  • 42 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信