Skip to content

Instantly share code, notes, and snippets.

@gthrm
Created February 18, 2022 12:53
Show Gist options
  • Save gthrm/157c8c94cc27a8a4dad64d9efac42a06 to your computer and use it in GitHub Desktop.
Save gthrm/157c8c94cc27a8a4dad64d9efac42a06 to your computer and use it in GitHub Desktop.
getByPath
export function getByPath(
path: string[] | string,
obj: Record<string, any>,
separator = "."
) {
const properties = Array.isArray(path) ? path : path.split(separator);
return properties.reduce((acc: Record<string, any>, item: string) => {
return acc[item];
}, obj);
}
const data = {
key1: {
key11: {
key111: "345"
},
key12: "123"
}
};
console.log(getByPath(["key1", "key11", "key111"], data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment