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

172
Vistas
react JavaScript ternary conditional operation

After I import the data as json from the detail page, in ProductDetail > brand > shoes > size.length get the length length is outputting in JSX.

But there is a problem. There are also products without shoes data for each detailed product on the detail page. I want to treat products without data as 0 instead of length as a ternary operator, but I don't know how to handle it.

<p>{ProductDetail && ProductDetail.brand.shoes.size.length}</p>

But here, data without brand is used using the ternary operator. <p>0</p> : I want to display it like this.

Nike Air Force ProductDetail > brand > shoes > size > length(0,1,2,3,4,5,6) <p>{length}</p>
jordan shoes ProductDetail > brand > shoes > size > length(0,1,2,3,4,5) <p>{length}</p>
adidas shoes ProductDetail > brand > x   -> Handles `<p>0</p>`.
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If you need to show 0 when an object is null or parent object is null, Try some like below

<p>{ProductDetail?.brand?.shoes?.size?.length || 0}</p>

Basically with using optional chaining and || operator, The output will be

ProductDetail is null/undefined ==> 0
ProductDetail.brand null/undefined ==> 0
....
ProductDetail.brand.shoes.size has valid array ==> length

let ProductDetail = { brand: { shoes: { size: [2, 3] } } };
console.log(ProductDetail?.brand?.shoes?.size.length || 0);

ProductDetail = null;
console.log(ProductDetail?.brand?.shoes?.size.length || 0);

ProductDetail = { brand: { shoes: null } }
console.log(ProductDetail?.brand?.shoes?.size.length || 0);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use ternary operator and optional chaining like this

<p>{ProductDetail?.brand?.shoes?.size?.length ? ProductDetail.brand.shoes.size.length : null}</p>
about 4 years ago · Juan Pablo Isaza 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