Ir para o conteúdo

CódigoNão tentada

getByPath (lodash.get)

Dificuldade: fácil

getByPath(obj, 'a.b[0].c', defaultValue), aceitando também um caminho em array como ['a', 'b', 0, 'c'].

  • retorne defaultValue só quando o resultado for undefined (null e 0 são valores reais)
  • nunca lance erro com null/undefined no meio do caminho
  • um caminho vazio retorna o próprio objeto

Bônus: infira o tipo de retorno a partir do caminho em string com template literal types.

Ver solução de referência
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;
}
Carregando editor…