Ad
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')
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
?
Ad
Answer
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)
Ad
source: stackoverflow.com
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad