Created
March 24, 2015 16:44
-
-
Save steve-codemunkies/78391c10d7b126d76b85 to your computer and use it in GitHub Desktop.
ObjectClone.js
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 getObjectType(obj) { | |
var funcNameRegex = /function (.{1,})\(/; | |
if(!!obj && !!obj.constructor) { | |
var results = (funcNameRegex).exec(obj.constructor.toString()); | |
return (results && results.length > 1) ? results[1] : ""; | |
} | |
return typeof obj; | |
} | |
function cloneArrayContents(sourceArray) { | |
var targetArray = []; | |
sourceArray.forEach(function(item) { | |
targetArray.push(clone(item)); | |
}); | |
return targetArray; | |
} | |
function clone(source) { | |
var target = {}; | |
for (var prop in source) { | |
var objectType = getObjectType(source[prop]); | |
if(objectType === 'Array') { | |
target[prop] = cloneArrayContents(source[prop]); | |
} else if(source[prop] === null) { | |
target[prop] = null; | |
} else if(objectType === 'object') { | |
target[prop] = clone(source[prop]); | |
} else { | |
target[prop] = source[prop]; | |
} | |
} | |
return target; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment