0

I have an entity class as fallow:

export class Contact {
  id: number;
  firstName: string;
  lastName: string;

  constructor(id?, firstName?, lastName?) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
  }
 
}

and want to have a different copy from Contact:

export class MyComponent {
  
  contactSrc = new Contact();
  contactDest = new Contact();
  
  constructor() {
      this.contactSrc.firstName = "Adam"
  }



  handleCopyOfObject() {
    console.log("firstName for contactSrc: " + this.contactSrc.firstName);

    this.contactDest = this.contactSrc;
    this.contactDest.firstName = "Mohsen";

    console.log("-----------result after copy -----------");
    console.log("firstName for contactSrc: " + this.contactSrc.firstName);
    console.log("firstName for contactDest: " + this.contactDest.firstName);
  }

}

the output is:

firstName for contactSrc: Adam
-----------result after copy -----------
firstName for contactSrc: Mohsen
firstName for contactDest: Mohsen

you can see that by changing contactDest.firstName, contactSrc.firstName also changes. how can I change contactDest.firstName without effecting the contactSrc.firstName?

SM. Hosseini
  • 171
  • 1
  • 13
  • Does this answer your question? [typescript - cloning object](https://stackoverflow.com/questions/28150967/typescript-cloning-object) – sinanspd Oct 03 '20 at 08:42
  • 1
    Quick fix: `this.contactDest = JSON.parse(JSON.stringify(this.contactSrc));` – ruth Oct 03 '20 at 08:44
  • Exactly, this worked! thank you Michael D! – SM. Hosseini Oct 03 '20 at 09:33
  • Can't see why this is a duplicate of a javascript question. Typescript or even Angular could have a new or extended version of any function that javascript does in any other way. – JoeCool Nov 28 '21 at 13:10

1 Answers1

0

Use spread operator or Object.assign();

contactSrc = {
    firstName : 'John';
}
contactDest = {...contactSrc, firstName : 'Doe'};