mirror of
https://gitlab.com/mbugroup/lti-web-client.git
synced 2026-05-20 13:32:00 +00:00
chore(FE-113): create getByPath helper function
This commit is contained in:
@@ -27,3 +27,37 @@ export const formatCurrency = (
|
||||
maximumFractionDigits,
|
||||
}).format(value);
|
||||
};
|
||||
|
||||
/**
|
||||
* Retrieves a nested value from an object using a dot-delimited key path.
|
||||
* Supports array indexes (e.g., "users.0.name") and returns a default value
|
||||
* if the path does not exist.
|
||||
*
|
||||
* @param obj - The source object to search.
|
||||
* @param path - Dot-delimited key string (e.g., "user.address.city").
|
||||
* @param defaultValue - Optional value to return if the key path is not found.
|
||||
* @returns The value found at the specified path, or the default value.
|
||||
*/
|
||||
export function getByPath<T, D = undefined>(
|
||||
obj: T,
|
||||
path: string,
|
||||
defaultValue?: D
|
||||
): unknown | D {
|
||||
if (obj == null) return defaultValue as D;
|
||||
if (!path) return obj as unknown;
|
||||
|
||||
const segments = path.split('.').filter(Boolean);
|
||||
let cur: { [key: string]: unknown } = obj;
|
||||
|
||||
for (const seg of segments) {
|
||||
if (cur == null) return defaultValue as D;
|
||||
const key: string | number =
|
||||
Array.isArray(cur) && /^\d+$/.test(seg) ? Number(seg) : seg;
|
||||
if (Object(cur) !== cur || !(key in cur)) {
|
||||
return defaultValue as D;
|
||||
}
|
||||
cur = cur[key] as { [key: string]: unknown };
|
||||
}
|
||||
|
||||
return cur as unknown;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user