mitesh jain
mitesh jain

Reputation: 139

New record Updating old record automatically in Array

Hi I am trying to store 2 rows in array but the second row is updating the first row already stored.

  UserRole: UserRoleDTO;
  UserRoleArray: UserRoleDTO[];     
  rolesstring=["1","2"]      
  this.roleidArray = rolesstring.split(',');
  let UserArrayData = [];
  let count = 0;
  for (let roledata of this.roleidArray) {
    this.UserRole.roleid = +roledata;
    this.UserRole.userid = +UserId;
    this.UserRole.isactive = 1;
    this.UserRole.entryby = 1;
    console.log('RoleId which need to store in UserArrayData :' + this.UserRole.roleid);
    UserArrayData[count] = this.UserRole;
    console.log('Data stored in UserArrayData :' + UserArrayData[count].roleid);
    count = count + 1;
  }
  this.UserRoleArray = UserArrayData;
  console.log('RoleId which is stored in UserArrayData[0]:' + UserArrayData[0].roleid);// here it is always showing the last roleid stored

The result for UserArrayData[0].roleid should be as 1 but it is displaying as 2.

Upvotes: 1

Views: 40

Answers (1)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

This is the issue with deep cloning, As whenever you assigning UserArrayData[count] = this.UserRole; it's assigning it's reference. So to over come this you need to assign deep copy to Object.assign.

Try this:

 UserArrayData[count] = Object.assign({}, this.UserRole);

Or as @JB suggested you can create a local variable inside fol loop.

Try this:

  for (let roledata of this.roleidArray) {
    let tmpObj = this.UserRole;
    tmpObj.roleid = +roledata;
    tmpObj.userid = +UserId;
    tmpObj.isactive = 1;
    tmpObj.entryby = 1;
    console.log('RoleId which need to store in UserArrayData :' + tmpObj.roleid);
    UserArrayData[count] = this.UserRole;
    console.log('Data stored in UserArrayData :' + UserArrayData[count].roleid);
    count = count + 1;
  }

Upvotes: 1

Related Questions