How can I reduce this if statement in JavaScript
if(obj.attributes && obj.attributes.email === 'test@test.com') { ... }
How can I reduce this if statement in JavaScript
if(obj.attributes && obj.attributes.email === 'test@test.com') { ... }
The line by it self is clear, however if you are looking a way to write less &&
operator inside you can always put things outside of the comparison such as.
var attributes = obj.attributes || {};
if ( attributes.email === 'test@test.com' ) {
}
This makes sense if you need to make multiple checks instead of a single one, however if is a single comparison it seems like the code you already have is okay as you are making sure attributes
is defined before accessing an undefined
property.
On the other hand if you have support for ES 2015 you can destruct stuff like:
const { attributes = {} } = obj;
if ( attributes.email === 'test@test.com' ) {
}
You can create a reusable get
function using Array.reduce()
. The function parameters are a path, the object, and a defaultValue (default defaultValue
is undefined
). It will iterate the path, and try to extract the value, if it fails, it will return the defaultValue
:
const get = (path, obj, defaultValue) => obj ?
path.reduce((r, k) => r && typeof r === 'object' ? r[k] : defaultValue, obj)
:
defaultValue;
if(get(['attributes', 'email'], null) === 'test@test.com') { console.log(1) }
if(get(['attributes', 'email'], {}) === 'test@test.com') { console.log(2) }
if(get(['attributes', 'email'], { attributes: {} }) === 'test@test.com') { console.log(3) }
if(get(['attributes', 'email'], { attributes: { email: 'test@test.com' } }) === 'test@test.com') { console.log(4) }
There is a TC39 stage proposal called "Optional Chaining for JavaScript". If it will make it's way to the language, it will add an the optional chaining operator - ?
. Now if attributes
don't exist, it will return undefined
.
Example: obj.attributes?.email
It's usable today via babel plugin.