I have an array of objects like this:
const arrA = [{a: true}];
And I create a copy of the array like so:
const arrB = Array.from(arrA);
But when I modify the value of the object in arrB, the value in arrA gets modified too.
arrB[0].a = false
// arrB = [{a:false}]
// arrA = [{a:false}] - gets modified also
How do I modify the object values in the cloned array without modifying the original array.
Array.from
creates what is called a shallow copy. Shallow copy means you have 2 variables- arrA
and arrB
pointing at the same array in memory, so you change one it changes the other. With objects inside its even more complicated- cuz even if you manage to create different array in memory- it might still point on the same objects as the previous array, leading to again- one change the changes both.
The opposite is deep copy- creating a new array with new objects that hold the same data values, not references. There are a few methods for that, you can read more here, I recommend on JSON.parse/stringify
as the easiest one:
const arrA = [{a: true}];
const arrB = JSON.parse(JSON.stringify(arrA));
This will give you what you want :)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments