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

227
Vistas
How to assign "null" when received data is undefined?

I am currently working on a project that collects product information of several stores. I have a problem when I'm assigning the scraped product data to an object that I want to store in a final array. Everything is going well except for when a product does not have an image.

 let productData = {
        productId: item.id, 
        title: item.title,
        price: item.price.now,
        unitSize: item.price.unitSize,
        productLink: item.link,
        productImage: typeof item.images[0].url == "undefined" ? null : item.images[0].url,
        availableOnline: item.availableOnline
      }
      productsArray.push(productData)
}

As you can see I'm trying to use a ternary operator to check if the value is undefined first. If the value is undefined I want to set the value of productImage to null instead of the whole application failing with the error that it's undefined. I also tried storing the value in a seperate variable first and check for that variable to be undefined or not but that wasn't working either.

Could anyone explain to me why the way I do it now is not working and what I should do in order to make it work?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Does item.images always have an array item at position zero? If not, you're trying to get the url property from an undefined object, which will throw an error.

You could add to this by first checking that item.images[0] exists:

{
  productImage: item.images[0] !== undefined && typeof item.images[0].url == "undefined" ? null : item.images[0].url,
}

Better yet, assuming you don't need IE compatibility, you could use Optional Chaining, and Nullish Coalescing as pointed out by robertklep in the comments.

{
  productImage: item.images[0]?.url ?? null,
}
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