Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!