Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add optional chaining to JSON object?

I am trying to compare a value within a JSON object with a variable:

if (resp.userdetails.name == username) {
// do something
}

The problem is that not all resp objects have userdetails, so I get this error message sometimes:

Cannot read properties of undefined (reading ‘name’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried to use ? to say it might be optional (or not exist):

if (resp.userdetails?.name == username)

But I get an Unexpected token error in that case.

Can someone please tell me how I can update my if statement to say userdetails may not always be in the response, but if it is, then check name is equal to username?

>Solution :

Either:

  • Use a JS engine which supports optional chaining
  • Use a tool like Babel to transpile your JS from a modern version of the language to an older one which doesn’t support optional chaining
  • Manually test for the object existing before you try to read a property from it
if (resp.userdetails && resp.userdetails.name == username)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading