Skip to content

Instantly share code, notes, and snippets.

@miguel-leon
Created August 14, 2019 16:21
Show Gist options
  • Save miguel-leon/ec8946e65475fc3d65fa8ca08c4e50af to your computer and use it in GitHub Desktop.
Save miguel-leon/ec8946e65475fc3d65fa8ca08c4e50af to your computer and use it in GitHub Desktop.
safely deep set nested object properties
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