4

I'm checking if a nested object item named "token" is empty or not, in AngularIDE with Angular4

if (typeof this.user.data.token !== "undefined")

this is throwing <Cannot read property 'token' of null>

Should I necessarily check for every nested object existance?

3
  • you can use lodash for checking nested properties Commented Sep 15, 2017 at 14:26
  • Can you make an example? Commented Sep 15, 2017 at 14:29
  • check for lodash get function in official docs Commented Sep 15, 2017 at 18:26

3 Answers 3

4

You have to ...

if (this.user && this.user.data && this.user.data.token) {
}
Sign up to request clarification or add additional context in comments.

Comments

1

Always keep in mind that undefined and null are different, when you see undefined it means that a variable was declared but it holds no value in it and null is an actual assignment value. Also undefined is a type and null is an object. So..

 if(!(this.user.data.token == null)); 

Should work for you, if you want to add some other conditions just and the operator || and type next condition.

If you're looking to check for undefined objects you can do something like

this.user.data.token != undefined && ... 

and so on..

Comments

0

You can create a reusable helper function which checks if the nested key exists or not and returns a boolean value.

/**
* @param obj: to check the nested key
* @param args: array of location to the nested key to check ['parentNode', 'childNode', 'grandChildNode']
*/
checkNestedKey(obj, args) {
    for (let i = 0; i < args.length; i++) {
        if (!obj || !obj.hasOwnProperty(args[i])) {
            return false;
        }
        obj = obj[args[i]];
    }
    return true;
}

// to check if value exist this.user.data.token
if (this.checkNestedKey(this.user, ['data', 'token'])) {
    // continue here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.