亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何根據角度8中的條件從對象數組中獲取最后一個對象

如何根據角度8中的條件從對象數組中獲取最后一個對象

智慧大石 2023-10-04 14:22:33
我有一些對象,我使用settimeout函數接收一個又一個對象,然后每次將其推入數組以填充到表中。這是在我的項目中動態出現的,但僅供參考,我settimeout在這里使用和硬編碼?,F在我的問題是,每當我使用 接收數據時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 關注
  • 112 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號