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.
Try the following
For more details check this question out What is the most efficient way to deep clone an object in JavaScript?
Same issue happen to me. I have data from service and save to another variable. When ever I update my array the copied array also updated. old code is like below
So when ever I change $scope.MyData also change $scope.MyDataOriginal. I found a solution that angular.copy right code as below
A nice way to clone an array of objects with ES6 is to use spread syntax:
MDN
You just need to use the '...' notation.
When you have an array say x, [...x] creates a new array with all the values of x. Be careful because this notation works slightly differently on objects. It splits the objects into all of its key, value pairs. So if you want to pass all the key value pairs of an object into a function you just need to pass function({...obj})
As mentioned Here
.slice(0)
will be effective in cloning the array with primitive type elements. However in your exampletags
array contains anonymous objects. Hence any changes to these objects in cloned array are reflected intags
array.@dangh's reply above derefences these element objects and create new ones.
Here is another thread addressing similar situation
Try