CódigoSin intentar
getByPath (lodash.get)
Dificultad: fácil
getByPath(obj, 'a.b[0].c', defaultValue), que también acepta una ruta en array como ['a', 'b', 0, 'c'].
- devuelve
defaultValuesolo cuando el resultado esundefined(nully0son valores reales) - nunca lances un error por
null/undefineda mitad de camino - una ruta vacía devuelve el propio objeto
Extra: infiere el tipo de retorno a partir de la ruta en string con template literal types.
Ver solución de referencia
export function getByPath(obj: unknown, path: string | readonly (string | number)[], defaultValue?: unknown): any { let keys: readonly (string | number)[]; if (typeof path === 'string') { // "a.b[0].c" → ["a", "b", "0", "c"] keys = path.replaceAll('[', '.').replaceAll(']', '').split('.').filter((key) => key !== ''); } else { keys = path; }
let current: any = obj; for (const key of keys) { if (current === null || current === undefined) { return defaultValue; } current = current[key]; } if (current === undefined) { return defaultValue; } return current;}
Ctrl Enter