chore(FE-113): create getByPath helper function

This commit is contained in:
ValdiANS
2025-10-21 15:01:19 +07:00
parent d550dcbf48
commit 0bab704163
+34
View File
@@ -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;
}