Skip to content

Instantly share code, notes, and snippets.

@92hackers
Created August 18, 2017 09:34
Show Gist options
  • Save 92hackers/e7784f61794a6dafabdea036bbc231d6 to your computer and use it in GitHub Desktop.
Save 92hackers/e7784f61794a6dafabdea036bbc231d6 to your computer and use it in GitHub Desktop.
javascript deep clone
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