I tried this approach:
this.plans = [];
this.plansCopy = [...this.plans];
Seems it does not work cause returns duplictions.
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With