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
?
CodePudding user response:
Either:
- Use a JS engine
Eg:-
var _ = require("lodash"); var data = [ { userdetails: { name: "d" } }, {}, { userdetails: {} }, { userdetails: { name: "d" } }, ]; for (i = 0; i < data.length; i ) { var resp = data[i]; if (_.get(resp, "userdetails.name") == "d") { // if (resp.userdetails && resp.userdetails.name == "d") { use without loadlash console.log("Success"); } else { console.log("failed"); } }
Here loadash is super complex. But you can use this to avoid runtime errors. Below both expressions get the same result
resp.userdetails && resp.userdetails.name == "d" === _.get(resp, "userdetails.name") == "d"