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);
 
 
 
Reply:
 
 
 
 
Instead you can use document.cloneNode() or object.CloneNode()
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
I think the last line:

var obj2= new cloneObject(obj2);

should be

var obj2= new cloneObject(obj1);
Typo. thanks for that.
rendered @ Wed Mar 26 14:15:19 CET 2014