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?

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
rocket
  • 253
  • 1
  • 2
  • 13
  • 1
    Can you please tell what is the value of `response.data.data.user_fk`. – Nikhil Goyal Jan 13 '20 at 15:31
  • Does this answer your question? [How to check a not-defined variable in JavaScript](https://stackoverflow.com/questions/858181/how-to-check-a-not-defined-variable-in-javascript) – Jordi Nebot Jan 13 '20 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. – Pointy Jan 13 '20 at 15:33
  • The goal is to test user_fk in response.data.data – rocket Jan 13 '20 at 15:37

2 Answers2

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
}
Link0
  • 655
  • 5
  • 17
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

qiAlex
  • 4,290
  • 2
  • 19
  • 35