get, or set value nested objects.
// 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