0

I copied obj1 to obj2 but when I make changes in obj2 the object obj1 value is also changing. How to stop this?

  let p24:   ProductModule=new ProductModule();
                              p24=  this.productlist[g];
                              p24.variants=[];
                              p24.variants.push(p.variants[h]);
                                  this.newproductlist.push(p24);

here this.productlist[g] is an array but when i perform p24.variants=[]; acction value inside this.productlist[g] also became empty

Midhilaj
  • 4,905
  • 9
  • 45
  • 88
  • https://stackoverflow.com/questions/28150967/typescript-cloning-object – JGFMK Feb 10 '19 at 08:41
  • `p24 = this.productlist[g];`**does not** create a copy, the `new ProductModule();` of the previous line isn't being used at all. – jonrsharpe Feb 10 '19 at 08:42

3 Answers3

1

There are multiple ways to clone object in Javascript.

Simplest way (Deep clone/copy);

p24=  JSON.parse(JSON.stringify(this.productlist[g]));

Note : By doing this, you may loose the original type of Object.

Or you can also look at Object.assign , Object.create and spread(...object) operator as suggested by JGFMK

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
1

When you assign javascript oject to another object, both will point to same memory location. that's the reason if you update on one obejct, the same will be updated another. To avoid this

Option 1 :

p24 =  JSON.parse(JSON.stringify(this.productlist[g]));

Option 2 :

p24 =   {...this.productlist[g]};
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27
1

Numbers are value types and objects are reference types:

enter image description here

So assigning an object variable to another object variable causes them both to reference (point to) the same object.

You need to copy the instance instead using one of the techniques shown in the other answers.

[NOTE: This syntax shown uses C# instead of TypeScript, but conceptually it works the same.]

DeborahK
  • 57,520
  • 12
  • 104
  • 129