Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda