簡體   English   中英

在 Angular 中使用 push 方法更新對象數組

[英]Update array of objects using push method in Angular

studentsOld: any[] = [
   { id: 1, name : 'test', age: 20 }, 
   { id: 2, name : 'sample', age: 21 }
];
 
studentsNew: any = [];

tmp = 0;
selcatage;
funedit(post) {
  this.tmp = post.name
  this.selcatage = post.age
}

funsave() {
  this.studentsOld.forEach((item, index) => {
    var obj;
    obj = {
      name: item.name,
      age: item.age
    }
    
    this.studentsNew.push(obj)
    this.tmp = 0
    this.fundata()
  });
  
  console.log(JSON.stringify(this.studentsNew))
}

我試過但沒有得到實際結果。 這是將對象推入新數組的正確方法嗎

樣品 output:

id:1的年齡 20 更新為 19 並顯示值 19 並且即使在頁面刷新后也顯示相同的值 19

你不需要迭代,但只需要

this.studentsNew = this.studentsOld;

console.log(JSON.stringify(this.studentsNew));

但是如果你想在里面添加一個新數據,你可以通過這種方式添加:

studentsOld: any[] = [
    { id: 1, name : 'test', age: 20 }, 
    { id: 2, name : 'sample', age: 21 }
 ];

 test(){
   this.studentsOld.push({
    id: 3, name : 'sample', age: 33
   })

   console.log("qui", this.studentsOld)
 }

無需聲明 var obj,您可以直接推送到數組,如下所示,並將預期 output 的年齡減 1:

studentsOld: any[] = [
   { id: 1, name : 'test', age: 20 }, 
   { id: 2, name : 'sample', age: 21 }
];
 
studentsNew: any = [];


funsave() {
  this.studentsOld.forEach((item, index) => {        
    this.studentsNew.push(obj)
    this.tmp = 0
    this.fundata({
      name: item.name,
      age: +item.age - 1
    })
  });
  
  console.log(JSON.stringify(this.studentsNew))
}

這使工作。 謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM