Home > OS >  how to copy array without references in Type script?
how to copy array without references in Type script?

Time:08-16

I want to coppy aray, but when i assign value both arrays are changing values.

 ngOnInit() {
     this.service.searchTickets().subscribe((resp) => {
  this.dataSource.data = resp.entities;
  this.records = [...this.dataSource.data];
  })

this function bellow is calling when i slide toggle and here i assign username.

displayValue(value: TicketsList) {
let index;
index = Number(value.key);

this.dataSource.data[value.key!].status = !this.dataSource.data[value.key!].status;
this.dataSource.data[index].supervisor = 'John Woor';
}

html file:

 <mat-slide-toggle
      (click)="displayValue(element)"
      [checked]="element.status"
    ></mat-slide-toggle>

Edit: This worked for me

   this.records = JSON.parse(JSON.stringify(this.dataSource.data));

CodePudding user response:

Please use loadash cloneDeep instead. It will create a deep copy and eliminate this problem!

ngOnInit() {
    this.service.searchTickets().subscribe((resp) => {
  this.dataSource.data = resp.entities;
  this.records = cloneDeep(this.dataSource.data);
  })

CodePudding user response:

You can use also Object.assign:

this.records = Object.assign([], this.dataSource.data);
  • Related