Created
May 20, 2021 08:38
-
-
Save arekko/033c766ef5e4556a12973ddc232ecce7 to your computer and use it in GitHub Desktop.
Get object path
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
import { type } from 'ramda'; | |
const isObject = (value: unknown) => type(value) === 'Object'; | |
export const getPath = ( | |
obj: Record<string, any>, | |
key: string, | |
path: string[] = [] | |
): string[] | undefined => { | |
if (!isObject(obj)) { | |
return; | |
} | |
for (const [k, v] of Object.entries(obj)) { | |
if (k === key) { | |
return [...path, k]; | |
} | |
if (isObject(v)) { | |
const result = getPath(v, key, [...path, k]); | |
if (result != null) return result; | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment