Created
March 29, 2012 06:46
-
-
Save Trindaz/2234277 to your computer and use it in GitHub Desktop.
Javascript object deep copy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function processObjWithRef(obj, result){ | |
if(obj==null || typeof obj != 'object'){ | |
//nothing really to do here - you're going to lose the reference to result if you try an assignment | |
} | |
if(obj instanceof Array) { | |
for(var i=0; i<obj.length; i++){ | |
result.push(); | |
processObjWithRef(obj[i], result[i]); | |
} | |
} | |
if(obj instanceof Object){ | |
for(var k in obj){ | |
var count=0; | |
if(obj[k]==null || typeof obj[k] != 'object'){ | |
result[k] = obj[k]; | |
}else if(obj[k] instanceof Array) { | |
result[k] = []; | |
processObjWithRef(obj[k], result[k]); | |
}else if(obj[k] instanceof Object){ | |
result[k] = {}; | |
for( var attr in obj[k]){ | |
processObjWithRef(obj[k], result[k]); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This fails while cloning a simple case:
var b = { a: 10, b: { ba: new Date(), bb: [ 1, 2, { bba: 'pp' } ] } }; var c = {}; processObjWithRef( b, c );
. Fails withTypeError: Cannot set property 'bba' of undefined