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

254
Visualizações
Is there a cleaner way to check if a deep nested node exists?

Using pure javascript -- no third party / lodash etc.

Given a user looking for the existence of a deep nested node, is there a cleaner way to ensure each parent node exists so as to not return undefined?

Keeping it simple, check that a nested prop has length before performing an action.

The problem is, especially when passing props, at any given node, you could end up with undefined.

Is there a way to avoid checking that each node exists like this:

if( !!Grandparent && !!Grandparent.Parent && !!Grandparent.Parent.child && !!Grandparent.Parent.child.prop3.length){
    // do something
}

Something more like this: (which I know is not correct as any node being undefined hoses the process).

if(!!Grandparent.Parent.child.prop3.length) {
    // do something
}

// OR

if(typeof Grandparent.Parent.child.prop3.length !== "undefined"){
    // do something
}

EX:

   Grandparent: {
        Parent: {
            child: {
                prop1: 'alpha',
                prop2: 'beta',
                prop3: [
                    item: {
                        name: 'first',
                        type: 'string'
                    },
                    item: {
                        name: 'second',
                        type: 'number'
                    }
                ]
            }
        }
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As commenters have indicated, modern JavaScript provides the optional chaining operator (?.), which you can use like this (as long as you're not still trying to support IE):

const
  grandparent = getObject(),
  itemsCount = grandparent?.parent?.child?.prop3?.length,
  oops = grandparent?.parent?.child?.length;
console.log(itemsCount ?? "No such property");
console.log(oops ?? "No such property");


function getObject(){
  return {
    parent: {
      child: {
        prop1: 'alpha',
        prop2: 'beta',
        prop3: [
          { item: { name: 'first', type: 'string' }},
          { item: { name: 'second', type: 'number' }}
        ]
      }
    }
  };
}

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