Created
January 26, 2020 09:38
-
-
Save fumihumi/0131b3207cd796db9914df1346ef50c8 to your computer and use it in GitHub Desktop.
get, or set value nested objects.
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
// ref: https://stackoverflow.com/questions/6906108/in-javascript-how-can-i-dynamically-get-a-nested-property-of-an-object | |
export function getValue<T>(obj: T, path: string): T { | |
if (!path) return obj; | |
const properties = path.split("."); | |
return getValue(obj[properties.shift()], properties.join(".")); | |
} | |
// ref: https://stackoverflow.com/questions/18936915/dynamically-set-property-of-nested-object | |
export function setValue<T>(obj: T, path: string, value: Pick<T, keyof T>): T { | |
const pList = path.split("."); | |
const key = pList.pop(); | |
const pointer = pList.reduce((accumulator, currentValue) => { | |
if (accumulator[currentValue] === undefined) accumulator[currentValue] = {}; | |
return accumulator[currentValue]; | |
}, obj); | |
pointer[key] = value; | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment