In my code I want to save an object that changes during the execution in an array inorder to use it after the execution of the function,so I tried to create a copy of it using this approach:
let copy=[...original]//original is the variable that changes during the execution
when I used this approach I noticed that the content of the copied array is the same as the last value of the original array.
Now I need a method that can keep all the states of the original array in one variable.
CodePudding user response:
I have the issue often as well. What you did only copied the memory references. Not the memory values.
Javascript doesn't make this easy. As a result, in our many production apps, we use the lodash cloneDeep function https://lodash.com/docs/4.17.15#cloneDeep
The only other way to do this is to loop and copy every individual value, recursively digging into every inner object.
Using the cloneDeep also has a side effect of detaching anything observing the variables like seen in Vue.
A silly second way to do this, and maybe easier if you are just debugging is
let copy = [...JSON.parse(JSON.stringify(original))]
Which will clone everything at that moment.
CodePudding user response:
You can give a try to structuredClone() method which help you in creating a deep clone of a given value using the structured clone algorithm.
// Create an object with a value
const original = { name: "Alpha" };
// Clone it
const clone = structuredClone(original);
// Change original object value in execution
original.name = 'Beta';
console.log(original); // { "name": "Beta" }
console.log(clone); // { "name": "Alpha" }
console.log(clone !== original); // true