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

127
Visualizações
Best way to check an attribute of an object that might be undefined

I have an object (oUsed) containing "blocked" fields of a grid. If a field is blocked, it's "true". If it's not blocked, it's undefined.

What can happen now is, that a whole line (x coordinate value) is not blocked. So the following code will fail, as it checks the attribute of an undefined object.

    let oUsed = {
      "x1":{
        "y2": true; 
        "y3": true;
      }
      "x3":{
        "y2": true;
      }
    }
    let iY = 2;

    for (let iX=1;iX <= 3; iX++) {
        if (oUsed[`x${iX}`][`x${iY}`]) {
          break;
        }
    }

Doing it in two steps works, but it's not very pretty.

    for (let iX=1;iX <= 3; iX++) {
      if (oUsed[`x${iX}`]) {
        if (oUsed[`x${iX}`][`x${iY}`]) {
          break;
        }
      }
    }

What's the best practice for this kind of check?

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Use Object.hasOwnProperty or Object.hasOwn

 if (oUsed.hasOwnProperty(`x${iX}`) && oUsed[`x${iX}`][`x${iY}`])

or

use like this

 if (oUsed[`x${iX}`] && oUsed[`x${iX}`][`x${iY}`]) {

or if Optional Chaining is supported by your target browser

if (oUsed[`x${iX}`]?.[`x${iY}`]) 
about 4 years ago · Santiago Trujillo 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