rashidnk
rashidnk

Reputation: 4292

Typescript keep a copy of object's initial state

im working on angular2 typescript project ,I just want to reset the object's key to '' after calling save( ) function , example is below

export class Events{
    event:any={ name : '', date : '',.........};
    eventOriginal=this.event;

    save(){

      //save(this.event)

      //after save, reset value to initial state

      this.event=this.eventOriginal;

    }

  }

but in console.log(this.event) the value is not cleared, both objects are same. i tried to assign value from constructor too, so, what is the proper way to reset keys of object in typescript ?

Upvotes: 1

Views: 2045

Answers (2)

Bala
Bala

Reputation: 512

The step eventOriginal=this.event; will just assign the reference in javascript.

The Object.assign() method should be used to copy the values of all enumerable own properties. like

eventOriginal = Object.assign({}, this.event);

and then later

this.event= Object.assign({}, this.eventOriginal);

Upvotes: 1

basarat
basarat

Reputation: 276085

When you assign an object to another you are only assigning the reference.

Quick fix

Clone the object using spread

export class Events{
    event={ name : '', date : '',.........};
    eventOriginal= {...this.event};

Upvotes: 2

Related Questions