Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clone array of objects TypeScript?

I tried this approach:

this.plans = [];
this.plansCopy = [...this.plans];

Seems it does not work cause returns duplictions.

like image 595
Alice Avatar asked Dec 12 '17 16:12

Alice


People also ask

How do you clone an array of objects?

4. Another method to copy a JavaScript array is using Array. from() , which will also make a shallow copy, as shown in this example: If an object or array contains other objects or arrays, shallow copies will work unexpectedly, because nested objects are not actually cloned.

How do I copy from one array to another in TypeScript?

If your arrays are not huge, you can use the push() method of the array to which you want to add values. The push() method can take multiple parameters so you can use the apply() method to pass the array to be pushed as a collection of function parameters. let newArray = []; newArray. push.

How do I copy an array element to another array in TypeScript?

Use the concat function, like so: var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA. concat(arrayB); The value of newArray will be [1, 2, 3, 4] ( arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).

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

assign(): By using the Object. assign() method, all enumerable properties of one or more source objects are copied to the target object. This method returns the modified target object. The properties of the target object are overwritten if they have the same key as properties in the sources.


1 Answers

The spread operator returns the individual items of the array. If these are already objects, then it's returning the references to those objects. It's the [] part that is creating a new array. Thus you have a new array, but it will still contain the same object references, so this.plans[0].oper() will call this.plansCopy[0].oper() at the same time as well.

Instead you need to clone each individual object. There are a lot of different ways to do this (create deep copy of the array or individual objects). If you only need one level of cloning you can do:

this.plansCopy = this.plans.map(obj => ({...obj}));

This will create a new array where each element is a copy of each object.

like image 56
Explosion Pills Avatar answered Oct 20 '22 01:10

Explosion Pills