Last active
February 24, 2019 08:34
-
-
Save Duobe/fe5c40e756c8a28b375d33eec0ce7996 to your computer and use it in GitHub Desktop.
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
function deepCopy (target) { | |
if ( | |
target === null | |
|| typeof target === 'number' | |
|| typeof target === 'boolean' | |
|| typeof target === 'string' | |
|| typeof target === undefined | |
) return target | |
if (Array.isArray(target)) { | |
return target.map(item => deepCopy(item)) | |
} | |
if (target instanceof Date) { | |
return new Date(target) | |
} | |
if (typeof target === 'object') { | |
const _obj = {} | |
for (const key in target) { | |
_obj[key] = deepCopy(target[key]) | |
} | |
return _obj | |
} | |
return undefined | |
} |
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
function deepGet (obj, path) { | |
const arr = path.split('.') | |
for (const item of arr) { | |
if (obj[item] === undefined) return undefined | |
obj = obj[item] | |
} | |
return obj | |
} |
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
function deepSet(obj, path, value) { | |
const arr = path.split('.') | |
for (let i = 0; i < arr.length; i++) { | |
if (i === arr.length - 1) { | |
obj[arr[i]] = value | |
} else if (obj[arr[i]] === undefined) { | |
obj = obj[arr[i]] = {} | |
} else { | |
obj = obj[arr[i]] | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment