0

I am using the Object class of JavaScript to check if a variable exists before using it from a JSON response.
When I try to call that line of code I get this error

Cannot convert undefined or null to object
at Function.keys ()
at successCallback

Here is my attempt:

if (Object.keys(response.data.data.user_fk)) {
  $rootScope.username = response.data.data.user_fk.name;
}

Please how can I get the check right?

4
  • 1
    Can you please tell what is the value of response.data.data.user_fk. Commented Jan 13, 2020 at 15:31
  • Does this answer your question? How to check a not-defined variable in JavaScript Commented Jan 13, 2020 at 15:31
  • 1
    If you're trying to check whether user_fk is a property of response.data.data, then Object.keys() is not useful. You can test "user_fk" in response.data.data instead. Commented Jan 13, 2020 at 15:33
  • The goal is to test user_fk in response.data.data Commented Jan 13, 2020 at 15:37

2 Answers 2

1

If you just want to check if response.data.data.user_fk exists just use:

if (response.data.data.user_fk) {
    $rootScope.username=response.data.data.user_fk.name;
}

Be aware that if user_fk is a false or a 0 (everything that results to false when called within Boolean function), this will not trigger code inside if.

Boolean(0) //false
Boolean(false) //false
Boolean([]) //true
Boolean({}) //true
Boolean(true) //true

In such cases just compare it to undefined or null:

if (value !== undefined && value !== null) {
    //Execute code that uses value
}
Sign up to request clarification or add additional context in comments.

Comments

0
...
if(Object.keys(response.data.data.user_fk)){
...

With given question I only can say that

response or response.data or response.data.data or response.data.data.user_fk is undefined or null

So probably you receive null somewhere or missing data during some manipulations. But in provided question there is not enough data to answer more concrete

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.