Skip to content

Instantly share code, notes, and snippets.

@fumihumi
Created January 26, 2020 09:38
Show Gist options
  • Save fumihumi/0131b3207cd796db9914df1346ef50c8 to your computer and use it in GitHub Desktop.
Save fumihumi/0131b3207cd796db9914df1346ef50c8 to your computer and use it in GitHub Desktop.
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