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

236
Visualizações
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 Respostas
Responde à pergunta

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 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