-
-
Save guillaumegarcia13/78305f07de61f515160415497bb703d6 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
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 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