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

168
Views
How to handle JavaScript objects (parsed JSON) that contain null?

I'm using JavaScript/jQuery to fetch data as json via an ajax call. The json is then parsed to a JavaScript object. Let's call the object var.

Now I want to assign a value from the object to a variable:

let publicationDay = val["work-summary"][0]["publication-date"]["day"]["value"]

This works, as long this value exists. However, for some results, the object contains null not for ["value"] but for ["day"] (as shown below)

val["work-summary"][0]["publication-date"]["day"] // is null

In this case, let publicationDay = val["work-summary"][0]["publication-date"]["day"]["value"] will throw the following error:

Uncaught TypeError: val['work-summary'][0]['publication-date'].day is null

and the code execution is stopped. Sure, I can check whether val["work-summary"][0]["publication-date"]["day"] === null, but what would be the most elegant way to handle this case? Maybe, in the future even

val['work-summary'][0]['publication-date'] // is null

may occur and my check for null does not work.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Depends heavily on your context but here’s some examples.

const publicationDate = val['work-summary'][0]['publication-date'];

// usage
console.log(publicationDate && publicationDate.day && publicationDate.day.value); // very basic
console.log(publicationDate?.day?.value); // optional chaining, better if supported by your environment (should be)
console.log(get(publicationDate, “day.value”)); // lodash get()

about 4 years ago · Juan Pablo Isaza Report

0

I would recommend trying optional chaining. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Assuming that any of those values could be null:

let publicationDay = val?.["work-summary"]?.[0]?.["publication-date"]?.["day"]?.["value"]

It will set the variable to either day.value or undefined

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!