Consider an object, user
:
user = {
profile: {
first_name: "Arthur",
last_name: "Dent"
},
planet: "Earth"
}
What is the best way to check for existence of user.profile.first_name
?
I'd normally use (!!user && !!user.profile && !!user.profile.first_name)
but that can't possibly be the best way (especially in longer cases, where there's deeper nesting of attributes).
Curious how this is customarily done!
[EDIT] Consider, for the sake of argument, that you need to check the existence of users.jordan.profile.favorites.color
(intentionally long and ungainly), where you cannot be sure of the existence of any individual attribute (so perhaps users.jordan
exists but users.jordan.profile
does not.)
Granted, this is perhaps a sign of more pervasive problems in your code (e.g. you shouldn't create objects unless all possible attributes are populated) but at times, this can't be helped.