22-04-2009

Javascript Copy or clone javascript array / object

To make an independent copy of an array rather than a copy of the refence to it, you can use the array slice method.

var oldArray = ["mip", "map", "mop"];
var newArray = oldArray.slice();

To copy or clone an object :

function cloneObject(source) {
    for (i in source) {
        if (typeof source[i] == 'source') {
            this[i] = new cloneObject(source[i]);
        }
        else{
            this[i] = source[i];
	}
    }
}
 
var obj1= {bla:'blabla',foo:'foofoo',etc:'etc'};
 
var obj2= new cloneObject(obj1);
 
 
 

Comments:

6 comments.
Your comment:

»
cleerline 21/10/2009, 11:25 pm
I think the last line:

var obj2= new cloneObject(obj2);

should be

var obj2= new cloneObject(obj1);
joriso 22/10/2009, 10:29 pm
Typo. thanks for that.
Saravanan 06/07/2010, 2:44 pm
Instead you can use document.cloneNode() or object.CloneNode()
Sayyid 05/12/2010, 5:50 am
cloneNode only works for DOM objects, not all JS objects.
See also http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object
Wookie 08/03/2013, 1:32 pm
For some reason, although this appears to deep copy (clone) the array, if you use .length it returns undefined. Not 100% sure why tho'
Objects 17/05/2013, 7:29 pm
Slice does not work on Objects it only works on arrays.

 

[x]