Update array of objects using push method in Angular

553 views Asked by At
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))
}

I tried but not getting actual result. Is this correct way to push objects into new array

Sample output:

Update the id:1's age 20 to 19 and display the value 19 and also show the same value 19 even after page refresh

2

There are 2 answers

1
corsaro On

you not need to iterate but only

this.studentsNew = this.studentsOld;

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

but if you want to add a new data inside you can add on this way:

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)
 }
1
Jai Saravanan On

Instead of declaring to var obj, you can push directly to the array as below and subtract the age by 1 for your expected output:

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

This make work. Thanks!