Skip to content

Instantly share code, notes, and snippets.

@ksafranski
Created August 18, 2023 19:03
Show Gist options
  • Save ksafranski/9f5438e82a5ff144e2bc19a726d163a5 to your computer and use it in GitHub Desktop.
Save ksafranski/9f5438e82a5ff144e2bc19a726d163a5 to your computer and use it in GitHub Desktop.
Lodash `get` alternative
describe('get', () => {
it('return undefined on non-existent key', () => {
const res = get({ hello: 'world' }, 'foo');
expect(res).toBeUndefined();
});
it('returns key when nested', () => {
const res = get({ hello: { world: false } }, 'hello.world');
expect(res).toEqual(false);
});
});
export const get = <T>(obj: T, path: string): any => {
const paths: string[] = path.split('.'); // array of path keys
let currentNode: T = obj; // pointer to current node, start at root
let value: any = undefined; // placeholder for eventual value
// Loop nodes of path as pointer
for (const p of paths) {
if (typeof currentNode[p] === 'object') {
// Move pointer if object
currentNode = currentNode[p];
} else {
// Set value if last node
value = currentNode[p];
}
}
// value returned or undefined if not found
return value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment