Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/get-exact-key.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@layerstack/utils': patch
---

fix(get): Read a key spelled exactly as the path (e.g. `{ "a.b": 1 }`) before following it as a nested path
17 changes: 17 additions & 0 deletions packages/utils/src/lib/get.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,21 @@ describe('get', () => {
expect(get(obj, '["key.with.dots"]')).toBe('dots');
expect(get(obj, '["key[with]brackets"]')).toBe('brackets');
});

it('reads a key containing a period as that key', () => {
expect(get({ 'temp.max': 5 }, 'temp.max')).toBe(5);
expect(get({ 'a[0]': 'bracket' }, 'a[0]')).toBe('bracket');
});

it('prefers a key spelled exactly as the path over the nested value', () => {
expect(get({ 'a.b': 'flat', a: { b: 'nested' } }, 'a.b')).toBe('flat');
});

it('falls back to the path when no exact key exists', () => {
expect(get({ a: { b: 'nested' } }, 'a.b')).toBe('nested');
});

it('returns defaultValue when the exact key holds undefined', () => {
expect(get({ 'a.b': undefined }, 'a.b', 'default')).toBe('default');
});
});
9 changes: 9 additions & 0 deletions packages/utils/src/lib/get.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ function parsePath(path: string): (string | number)[] {
}

/**
* Read a value by key or path (`a.b`, `a[0].b`, `a["key"]`). A key spelled exactly as the path
* is read first, so `get({ "a.b": 1 }, "a.b")` is `1`.
*
* See: https://github.com/angus-c/just/blob/d8c5dd18941062d8db7e9310ecc8f53fd607df54/packages/object-safe-get/index.mjs#L33C1-L61C2
*/
export function get<T = any>(
Expand All @@ -78,6 +81,12 @@ export function get<T = any>(
return defaultValue as T;
}

// A key spelled exactly as given (`{ "a.b": 1 }`) wins over reading it as a path
if (typeof propsArg === 'string' && propsArg in Object(obj)) {
const value = obj[propsArg];
return value === undefined ? (defaultValue as T) : value;
}

let props: (string | number | symbol)[];

if (Array.isArray(propsArg)) {
Expand Down
Loading