Skip to content

Instantly share code, notes, and snippets.

@sstur
Created November 21, 2013 06:31
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sstur/7576927 to your computer and use it in GitHub Desktop.
Save sstur/7576927 to your computer and use it in GitHub Desktop.
Deep-copy an object, similar to calling JSON.parse(JSON.stringify(obj)) but preserves dates and undefined
function clone(obj) {
if (Object(obj) !== obj) return obj;
if (typeof obj.toJSON == 'function') {
return obj.toJSON();
}
var type = toString.call(obj).slice(8, -1);
if (type in CLONE) {
return CLONE[type].call(obj, clone);
}
var copy = {};
var keys = Object.keys(obj);
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
copy[key] = clone(obj[key]);
}
return copy;
}
var CLONE = {
'Array': function(clone) {
return Array.prototype.map.call(this, clone);
},
'Date': function() {
return new Date(this.valueOf());
},
'String': String.prototype.valueOf,
'Number': Number.prototype.valueOf,
'Boolean': Boolean.prototype.valueOf
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment