Home > database >  How to assign "null" when received data is undefined?
How to assign "null" when received data is undefined?

Time:07-05

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?

CodePudding user response:

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,
}
  • Related