Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 258
jsbisht Avatar asked Feb 12 '15 16:02

jsbisht


People also ask

How do I copy one array to another in JavaScript?

“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 = [].

Does array slice deep copy?

slice() , Array. from() , Object. assign() , and Object. create() ) do not create deep copies (instead, they create shallow copies).


2 Answers

Try

var copy = JSON.parse(JSON.stringify(tags)); 
like image 174
dangh Avatar answered Oct 04 '22 13:10

dangh


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?

like image 22
Marko Avatar answered Oct 04 '22 13:10

Marko