Skip to content

Instantly share code, notes, and snippets.

@four43
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save four43/f93647e8feaa54713cfe to your computer and use it in GitHub Desktop.

Select an option

Save four43/f93647e8feaa54713cfe to your computer and use it in GitHub Desktop.
Javascript Deep Copy with Depth
/**
* Deep Copy
*
* Creates a new object, copying the variables one by one into it.
* Available as a GitHub Gist: https://gist.github.com/four43/f93647e8feaa54713cfe
* @param {Object|Array} input The input object or array to copy.
* @param {Number} [maxDepth] The max depth the function should recurse before passing by reference, default: 5
* @param {Number} [depth] Starts at 0, used by recursion
* @returns {Object|Array}
* @private
*/
Object.prototype._deepCopy = function (input, maxDepth, depth) {
if (maxDepth === undefined) {
maxDepth = 5;
}
if (depth === undefined) {
depth = 0;
}
if(depth > maxDepth) {
return null;
}
// Handle the 3 simple types, and null or undefined
if (input === null || input === undefined || typeof input !== "object") {
return input;
}
// Date
if (input instanceof Date) {
var dateCopy = new Date();
dateCopy.setTime(input.getTime());
return dateCopy;
}
// Array
if (input instanceof Array) {
var arrayCopy = [];
for (var i = 0, len = input.length; i < len; i++) {
arrayCopy[i] = this._deepCopy(input[i], maxDepth, depth + 1);
}
return arrayCopy;
}
// Object
if (input instanceof Object) {
var newObj = {};
for (var prop in input) {
if (input.hasOwnProperty(prop)) newObj[prop] = this._deepCopy(input[prop]);
}
return newObj;
}
}
@four43
Copy link
Copy Markdown
Author

four43 commented May 20, 2014

Adding some limits (improvements?) to: http://stackoverflow.com/a/728694/387851

@four43
Copy link
Copy Markdown
Author

four43 commented Aug 7, 2014

Added comment section.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment