Object initialization

Hi all!

I have this Interface:

export interface UserDataInterfaceFirestore {
    user_name?: string;
    user_email: string;
...
}

… and I have initialized (in a global provider) an object with values.

I want to initialize a new object to populate with new values, but starting the same values the global object.

The problem occurs when I do the following:

private localUserData: UserDataInterfaceFirestore;

this.localUserData = this.global.userData;

I want to modify only this.localUserData, but when I modify an attribute in this.localUserData it automaticaly is updated also in this.global.userData.

Can anybody help me with this? I think is a fundamental misconception from my side, but I don’t know how to solve it.

Thanks!

Solved:

this.localUserData = { ...this.global.userData };

To clone the object attributes

That’s a shallow copy. Which is good enough if all your properties are strings like your code snippet. But if some of your properties are complex, like arrays, you need a deep copy. See the discussion of cloning here.

Incidentally, this is a common source of bugs in Javascript. I avoid it by using the immutable.js library and some other techniques. My recommendation is that it’s worth it to make all your variables immutable.

1 Like

Thanks for the info!