Created
October 2, 2021 01:02
-
-
Save Oaphi/fbcca0d7d3c8647356d705902e88f7f6 to your computer and use it in GitHub Desktop.
Deep lens into an object
This file contains hidden or 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
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