Check property without nesting if

Hey,
I’ve just a dumb Javascript question. For example, I want to check, if a user has the property Meteor.user().profile.fullname. Now there is a point, where Meteor.user() isn’t defined because the user is logging in. At the moment, I’m checking in by the following code (it’s in a autorun):

if(Meteor.user())
{
   if(Meteor.user().profile)
   { 
      if(Meteor.usert().profile.hasOwnProperty('fullname');
   }
}

This is a little bit long. On some other code I saw something like this:

if(doc&&doc.profile&&doc.profile.name)

But if I do this with Meteor.user(), I stell get type errors if Meteor.user() isn’t defined.

Is there any pattern how I can reduce my first code?

Take a look at brototype (and yes the bro humour is a bit much, but the ideas are great).

You can also use lodash’s _.get().

1 Like

I’ve found the following to work well once you get used to it:

var level3 = (((test || {}).level1 || {}).level2 || {}).level3;

Stack Overflow Post
Original Article

1 Like