Last active
August 28, 2017 16:03
-
-
Save kukiron/a6440b135967b7cc499d34d00e330868 to your computer and use it in GitHub Desktop.
Deep Cloning JavaScript Objects
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 deepClone(obj){ | |
// in case of premitives | |
if(obj===null || typeof obj !== "object"){ | |
return obj; | |
} | |
// handle date objects | |
if(obj instanceof Date){ | |
return new Date(obj.getTime()); | |
} | |
// handle Array | |
if(Array.isArray(obj)){ | |
var clonedArr = []; | |
obj.forEach(function(element){ | |
clonedArr.push(deepClone(element)); | |
}); | |
return clonedArr; | |
} | |
// lastly, handle objects | |
let clonedObj = new obj.constructor(); | |
for(var prop in obj){ | |
if(obj.hasOwnProperty(prop)){ | |
clonedObj[prop] = deepClone(obj[prop]); | |
} | |
} | |
return clonedObj; | |
} | |
var newObj = { | |
name: "Paddy", | |
address: { | |
town: "Lerum", | |
country: "Sweden" | |
} | |
}; | |
var newArr = [ [ {a: 'b'} ], [ {c: 'd'} ], [ {1: '2'} ] ]; | |
deepClone(newObj); | |
deepClone(newArr); | |
// Other shallow cloning methods -- | |
// for ES6 Object.assign: | |
// Object.assign({}, newObj); | |
// for JSON: | |
// JSON.parse(JSON.stringify(newObj)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment