Created
October 23, 2020 21:40
-
-
Save valorad/5cb857d77e25968ee510a22d396a93b8 to your computer and use it in GitHub Desktop.
TypeScript set nested key
This file contains hidden or 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
/** | |
* 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