Skip to content

Instantly share code, notes, and snippets.

@arekko
Created May 20, 2021 08:38
Show Gist options
  • Save arekko/033c766ef5e4556a12973ddc232ecce7 to your computer and use it in GitHub Desktop.
Save arekko/033c766ef5e4556a12973ddc232ecce7 to your computer and use it in GitHub Desktop.
Get object path
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