Copying an array of objects into another array in javascript using slice(0) and concat() doesnt work.
I have tried the following to test if i get the expected behaviour of deep copy using this. But the original array is also getting modified after i make changes in the copied array.
var tags = []; for(var i=0; i<3; i++) { tags.push({ sortOrder: i, type: 'miss' }) } for(var tag in tags) { if(tags[tag].sortOrder == 1) { tags[tag].type = 'done' } } console.dir(tags) var copy = tags.slice(0) console.dir(copy) copy[0].type = 'test' console.dir(tags) var another = tags.concat() another[0].type = 'miss' console.dir(tags)
How can i do a deep copy of a array into another, so that the original array is not modified if i make a change in copy array.
“concat()” is another useful JavaScript method that can assist you in copying array elements. In the concat() method, you can take an empty array and copy the original array elements to it. It will create a fresh copy of the specified array. var array2 = [].
slice() , Array. from() , Object. assign() , and Object. create() ) do not create deep copies (instead, they create shallow copies).
Try
var copy = JSON.parse(JSON.stringify(tags));
Try the following
// Deep copy var newArray = jQuery.extend(true, [], oldArray);
For more details check this question out What is the most efficient way to deep clone an object in JavaScript?
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