Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript object deep copy
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]);
}
}
}
}
}
@scottoffen

This comment has been minimized.

Copy link

scottoffen commented Aug 22, 2014

What is line 13 suppose to be counting?

@jbmonroe

This comment has been minimized.

Copy link

jbmonroe commented Feb 28, 2015

Probably our ability to detect a leftover variable. 😄 Should be using Array.isArray() to detect arrays, probably, and using "===" for comparison against null. The last loop would be a lot faster using function variables rather than if() tests, but one would have to use typeof instead of instanceof in order to make that work.

@mercmobily

This comment has been minimized.

Copy link

mercmobily commented Jun 28, 2015

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 with TypeError: Cannot set property 'bba' of undefined

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.