Skip to content

Instantly share code, notes, and snippets.

@valorad
Created October 23, 2020 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valorad/5cb857d77e25968ee510a22d396a93b8 to your computer and use it in GitHub Desktop.
Save valorad/5cb857d77e25968ee510a22d396a93b8 to your computer and use it in GitHub Desktop.
TypeScript set nested key
/**
* Sets a value of nested key string descriptor inside a Object.
* It changes the passed object.
* Ex1:
* let obj = {a: {b:{c:'initial'}}};
* setNestedKey(obj, ['a', 'b', 'c'], 'changed-value');
* assert(obj === {a: {b:{c:'changed-value'}}});
*
* Ex2:
* let obj = null;
* setNestedKey(obj, ['a', 'b', 'c'], 'new-value');
* assert(obj === {a: {b:{c:'new-value'}}});
*
* @param {[Object]} obj Object to set the nested key
* @param {[Array]} path An array to describe the path(Ex: ['a', 'b', 'c'])
* @param {[Object]} value Any value
*/
const setNestedKey: (obj: any, path: string[], value: any) => void
= (obj, path, value) => {
if (path.length === 1) {
obj[path[0]] = value;
return;
}
if (!obj[path[0]]) {
obj[path[0]] = {};
}
return setNestedKey(obj[path[0]], path.slice(1), value);
}
export default (obj: any, path: string[], value: unknown) => {
if (!obj) {
obj = {};
}
return setNestedKey(obj, path, value);
}
// Credit: https://stackoverflow.com/a/49754647/6514473
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment