Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning objects TypeScript [duplicate]

I am working with Angular 2 with TypeScript. I have User Management component where I have table of whole users.

When any user in table is clicked then forms appeaer with his whole properties to edit. Choosing user occurs event as below:

 onUserSelected(event) {         var selectedId = event.data.id;         this.selectedUser = this.users.filter(user => user.id === selectedId)[0]     } 

The problem is when selectedUser is being edited his properties also changes in table and it doesnt look so good. I tried to create copy myself as below but it didn't help - user class

 clone() {         var cloned = new User(this.id, this.login, this.name, this.surname, this.phone);         return cloned;     } 

Maybe I am doing something which is not good practice in Angular2?

like image 791
miechooy Avatar asked Jan 28 '17 08:01

miechooy


People also ask

How do I copy properties from one object to another in TypeScript?

The Object. assign() function can be used to copy all enumerable own properties from one or more source objects to a target object. This function returns the target object to the newObject variable. Here's an example of copying by assigning in TypeScript.

How do you clone an array of objects in TypeScript?

To create a deep copy of an array in TypeScript, install and use the lodash. clonedeep package. The cloneDeep method recursively clones a value and returns the result. The cloneDeep method returns an array of the correct type.

How can we copy object without mutating?

Similar to adding elements to arrays without mutating them, You can use the spread operator to copy the existing object into a new one, with an additional value. If a value already exists at the specified key, it will be overwritten.


2 Answers

Try using

this.user = Object.assign({}, currentObject); 

As mentioned by @AngularFrance, this will only work for shallow-copying objects, seek another implementation if there's a need to deep-copy an object.

like image 199
Amit Avatar answered Oct 08 '22 23:10

Amit


You can use lodash :

https://lodash.com/docs#cloneDeep

lodash is recommended for lot of objects / array manipulations

like image 22
almog Avatar answered Oct 09 '22 00:10

almog