Copying an array of objects into another array in javascript (Deep Copy)

jsbisht picture jsbisht · Feb 12, 2015 · Viewed 43.6k times · Source

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.

Answer

dangh picture dangh · Feb 12, 2015

Try

var copy = JSON.parse(JSON.stringify(tags));