Saltar al contenido

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 defaultValue solo cuando el resultado es undefined (null y 0 son valores reales)
  • nunca lances un error por null/undefined a 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;
}
Cargando editor…