Manush
Manush

Reputation: 1942

take copy of an array without affecting original array in Angular 2

Here is my code given Below:

this.service.content(data).subscribe(
  data => {
        this.array1= data.Result;
        this.array2= data.Result;
        /* Adding Additional Properties */
        this.array2.forEach(function(el:any){
          el.isActive = false;
        });
  }

When is add an item to array2 as you see in the code. Unfortunately, the item gets added into array1 as well. Kindly, provide solution to add property to array2 without affecting the value of array1.

And i also tried slice property to data.Result, but it didn't worked as expected.

Upvotes: 0

Views: 3187

Answers (3)

maxime1992
maxime1992

Reputation: 23813

This should work as expected :

this.service.content(data).subscribe(
  data => {
    this.array1 = data.Result;

    this.array2 = this
      .array1
      .map(el => Object.assign({}, el, { isActive: false }));
  }

EDIT :
If you use Typescript 2.1 or +, you can also use the spread operator on an Object like that :

this.service.content(data).subscribe(
  data => {
    this.array1 = data.Result;

    this.array2 = this
      .array1
      .map(el => ({...el, isActive: false }));
  }

Upvotes: 4

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41447

Assuming you are using ES6 you can use load lodash for deep copy

this.array1= _.cloneDeep(data.Result);
this.array2= _.cloneDeep(data.Result);

or use object.assign

this.array1= data.Result.map(function(obj) {
    Object.assign({}, obj)
})

this.array2= data.Result.map(function(obj) {
    Object.assign({}, obj)
})

Upvotes: -2

Monicka
Monicka

Reputation: 505

Assigning the Array is not making a copy of the array. The way you did it, you have created two pointers pointing to the same array. Changing the one pointer changes the original array. My point is:

data: any[];
array1: any[];
array2: any[];
data = ["1", "2"];
this.array1 = this.data;
this.array2 = this.data;

this.array1[0] = "3";

This will change the original array data and will put on position 0 the value 3.

You should copy the array not assign it.

You can find here good exampels

Upvotes: -1

Related Questions