Created
February 18, 2022 12:53
-
-
Save gthrm/157c8c94cc27a8a4dad64d9efac42a06 to your computer and use it in GitHub Desktop.
getByPath
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
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