Angular-2 : Copy one object to another

I wants to copy my class object to temp object.

Class properties:

export class PageModel {       
    AppID: any = null;
    ParentID: any = null;
    Type: any = null;
    Order: any = null;
    IsEnabled: boolean = false;
    View: any = null;
    Toolbars: any = null;
    Attachments: any = null;
} 

My initial object :

pageModel : PageModel =new PageModel();
pageModel.Type='New';
pageModel.Order=1;

Now i wants to assign this updated object to any temp object, this temp object is going to assign as model in one of the form, so only on Save button click i wants to update my main object.

I just need help, how to copy main object to temp one.

Upvotes: 1

Views: 1334

Answers (2)

Tushar Ghosh
Tushar Ghosh

Reputation: 1022

Alexander's answer is perfect for this problem. but some cases it's not work properly like as

{ a: 0 , b: { c: 0}} ;

so you can use, it's also work for deep clone

tempObject = JSON.parse(JSON.stringify(pageModel));

Please see the bellow example:

let obj1 = { a: 0 , b: { c: 0}};
  let obj2 = Object.assign({}, obj1);
  console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}

  obj1.a = 1;
  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
  console.log(JSON.stringify(obj2)); // { a: 0, b: { c: 0}}

  obj2.a = 2;
  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 0}}
  console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 0}}

  obj2.b.c = 3;
  console.log(JSON.stringify(obj1)); // { a: 1, b: { c: 3}}
  console.log(JSON.stringify(obj2)); // { a: 2, b: { c: 3}}

  // Deep Clone
  obj1 = { a: 0 , b: { c: 0}};
  let obj3 = JSON.parse(JSON.stringify(obj1));
  obj1.a = 4;
  obj1.b.c = 4;
  console.log(JSON.stringify(obj3)); // { a: 0, b: { c: 0}}

for more info please visit this link

Upvotes: 0

Alexander Ciesielski
Alexander Ciesielski

Reputation: 10834

tempObject = Object.assign({}, tempObject, pageModel);

This will create a new object, assign all properties of tempObject to it and then assign all properties of pageModel to it.

Upvotes: 3

Related Questions