Angular4 - check if nested object item is empty

Viewed 8143

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 Answers

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
}
Related