Created
August 18, 2017 09:34
-
-
Save 92hackers/e7784f61794a6dafabdea036bbc231d6 to your computer and use it in GitHub Desktop.
javascript deep clone
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
const isArray = arr => Object.prototype.toString.call(arr) === '[object Array]' | |
const isObject = obj => Object.prototype.toString.call(obj) === '[object Object]' | |
/** | |
* Deep copy properties from src, and return cloned object | |
* @param {Object} src source object to clone from | |
*/ | |
const deepClone = src => { | |
const dest = {} | |
const copy = (src, dest) => { | |
if (src) { | |
Object.keys(src).forEach(key => { | |
const value = src[key] | |
if (isArray(value)) { | |
dest[key] = value.map(item => item) | |
} else if (isObject(value)) { | |
dest[key] = {} | |
copy(src[key], dest[key]) | |
} else { | |
dest[key] = value | |
} | |
}) | |
} | |
} | |
copy(src, dest) | |
return dest | |
} | |
const a = { a: 12, b: [1, 2, 3, 4, 5], c: { d: { e: [5, 6, 7, 8] } } } | |
console.log('clone before: ', a) | |
const b = deepClone(a) | |
console.log('cloned b: ', b) | |
b.a = 78 | |
b.c.d.e = [] | |
b.b = [9,8] | |
console.log('b: ', b) | |
console.log('a: ', a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment