0

Currently I am using angular 2 and in my typescript file I have an object like this.

chartData: any

chartData has result array and each result is channel array

so chartData.result[0].channels[4], this is what we get initally

I want to push result[0] into result[1] and change channels[0].id = "New" and I am trying like

this.chartData.result.push(this.chartData.result[0]);

this.chartData.result[1].channels[0].id = "New"

When I am doing this, it changes id of channels[0] of both result[0] and result[1], why is this happening when I am trying to change only result[1] object.

code1
  • 8,351
  • 8
  • 27
  • 31
  • Possible duplicate of [Deep copy an array in Angular 2 + TypeScript](http://stackoverflow.com/questions/35504310/deep-copy-an-array-in-angular-2-typescript) – chrisbajorin Mar 27 '17 at 17:32
  • I linked a duplicate, but this really has nothing to do with angular/typescript. It's how javascript works. For future reference (ha), you're looking for info on "javascript pass by reference" – chrisbajorin Mar 27 '17 at 17:35

1 Answers1

0

Because you are binding pushing same object with its reference to an array element.May be doing below will help.

 this.chartData.result.push(Object.assign({}, this.chartData.result[0]));
Amir
  • 1,855
  • 3
  • 24
  • 40