Skip to content

Instantly share code, notes, and snippets.

@alexkhismatulin
Created January 24, 2019 17:45
Show Gist options
  • Save alexkhismatulin/22563f449efee3f3c22af41527d56429 to your computer and use it in GitHub Desktop.
Save alexkhismatulin/22563f449efee3f3c22af41527d56429 to your computer and use it in GitHub Desktop.
Simple deep cloning function. Works fine with primitive objects/arrays, doesn't work properly with class instances and objects with custom prototypes.
const isObject = value => typeof value === "object"
const cloneDeep = (value) => {
if (!value || !isObject(value)) return value
if (Array.isArray(value)) return value.map(item => cloneDeep(item))
return Object.keys(value).reduce((accum, propName) => {
const propValue = value[propName]
if (Array.isArray(propValue)) {
return { ...accum, [propName]: propValue.map(item => cloneDeep(item)) }
}
if (!isObject(propValue)) return { ...accum, [propName]: propValue }
return { ...accum, [propName]: cloneDeep(propValue) }
}, {})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment