Skip to content

Instantly share code, notes, and snippets.

@givingwu
Created June 26, 2019 10:56
Show Gist options
  • Save givingwu/fbbda23b9ab32f9b3a7f6480cfd0ad2f to your computer and use it in GitHub Desktop.
Save givingwu/fbbda23b9ab32f9b3a7f6480cfd0ad2f to your computer and use it in GitHub Desktop.
deepCopy & deepMerge Method in ECMAScript 6
export function deepCopy(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj
}
if (obj instanceof Date) {
return new Date(obj.getTime())
}
if (obj instanceof Array) {
return obj.reduce((arr, item, i) => {
arr[i] = deepCopy(item)
return arr
}, [])
}
if (obj instanceof Object) {
return Object.keys(obj).reduce((newObj, key) => {
newObj[key] = deepCopy(obj[key])
return newObj
}, {})
}
}
export function deepMerge(obj, ...args) {
for (let i = 0, l = args.length; i < l; i++) {
const o = args[i]
const ks = Object.keys(o)
for (let j = 0, k = ks.length; j < k; j++) {
const k = ks[j]
if (typeof k === 'object') {
obj[k] = deepCopy(o[k])
} else {
obj[k] = o[k]
}
}
}
return obj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment