Created
August 14, 2019 16:21
-
-
Save miguel-leon/ec8946e65475fc3d65fa8ca08c4e50af to your computer and use it in GitHub Desktop.
safely deep set nested object properties
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(value: any, obj: object, ...path: string[]) { | |
const target = path.slice(0, -1).reduce((p: any, k) => (p[k] = p[k] || {}), obj); | |
path.slice(-1).forEach(k => target[k] = value); | |
} | |
let o; | |
deepSet(99, o = { a: { x: 88 } }, ...'a.b.c'.split('.')); | |
console.log(o); | |
deepSet(99, o = { a: {} }, 'a'); | |
console.log(o); | |
deepSet(99, o = { a: {} }); | |
console.log(o); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment