Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

283
Visualizações
Typescript array of arrays of arrays: protect from undefined

I am parsing a complex object in Typescript, so have something like:

const a = reply['price']['value']['total']['value'];

and I like to ensure that all elements are defined in the chain, otherwise, it should set a=0 and do not trigger an exception if some of the chained keys are in fact undefined.

What would be the appropriate syntax for that?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you're using modern JS you can use nullish coalescing and optional chaining

const a = reply?.['price']?.['value']?.['total']?.['value'] ?? 0;

Try to avoid using || instead of ??, because that will give you 0, if the final value is any falsy value, like 0 or false.

If you don't want to use nullish coalescing, you can do this, which achieves the same.

const a = reply?.['price']?.['value']?.['total']?.['value'] ? reply['price']['value']['total']['value'] : 0;
about 4 years ago · Juan Pablo Isaza Relatório

0

If you can't use @nullptr 's answer, I suggest creating a function for that purpose :

function getObjectNestedValue2(obj, keys, defaultValue) {
    let currObjOrValue = obj;
    keys.forEach(key => {
        if (!currObjOrValue.hasOwnProperty(key)) {
            currObjOrValue = defaultValue;
            return;
        }
        currObjOrValue = currObjOrValue[key];
    });
    return currObjOrValue;
}

You then call it like so :

const a = getObjectNestedValue(reply, ['price', 'value', 'total', 'value'], 0);

Cheers

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda