Deep Copy object in Javascript
Full credit to [http://geniuscarrier.com/copy-object-in-javascript/][this webpage] who gathered several examples. This is just a nice reminder for me to have everything in the same place.
function deepCopy(oldObj) {
var newObj = oldObj;
if (oldObj && typeof oldObj === 'object') {
newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
for (var i in oldObj) {
newObj[i] = deepCopy(oldObj[i]);
}
}
return newObj;
}
Written by Esteban
Related protips
2 Responses
as far as i know JSON.parse(JSON.stringify(obj))
1 is faster sadly the page with the benchmarks is currently under development
over 1 year ago
·
Nice trick! as soon as it is up I'll test it :D thank you
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#