Created
January 24, 2019 17:45
-
-
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.
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 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