Skip to content

Instantly share code, notes, and snippets.

@Oaphi
Created October 2, 2021 01:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oaphi/fbcca0d7d3c8647356d705902e88f7f6 to your computer and use it in GitHub Desktop.
Save Oaphi/fbcca0d7d3c8647356d705902e88f7f6 to your computer and use it in GitHub Desktop.
Deep lens into an object
type NestedObj = {
[x: string]: string | number | boolean | null | undefined | NestedObj;
};
const lens = (obj: NestedObj, path: string) => {
const parts = path.split(".");
const [lastPart] = parts.slice(-1);
let current: NestedObj = obj;
for (const part of parts) {
const value = current[part];
if (typeof value === "object" && value) {
current = value;
}
if (part === lastPart || value === void 0) {
return value;
}
}
return;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment