Skip to content

Instantly share code, notes, and snippets.

@Duobe
Last active February 24, 2019 08:34
Show Gist options
  • Save Duobe/fe5c40e756c8a28b375d33eec0ce7996 to your computer and use it in GitHub Desktop.
Save Duobe/fe5c40e756c8a28b375d33eec0ce7996 to your computer and use it in GitHub Desktop.
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
}
function deepGet (obj, path) {
const arr = path.split('.')
for (const item of arr) {
if (obj[item] === undefined) return undefined
obj = obj[item]
}
return obj
}
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