Reputation: 3127
Is there a cleaner way to achive this?
const message = `Error message: ${json.email ? json.email[0] : ''}`
Upvotes: 0
Views: 283
Reputation: 1
When you use ternary operation, always return a value. Logical operators should be use with careful.
As logical expressions are evaluated from left to right, they are tested for possible "short-circuit" evaluation using the following rules:
Upvotes: 0
Reputation: 10528
In case you use lodash, you can use the _.get method, which lets you specify a whole path of nested property accessors and if any property along the path is not found it can optionally return a default value:
_.get(json, 'password[0]', '');
So your example would translate to something like this:
const message = `Error message: ${_.get(json, 'email[0]', '')} ${_.get(json, 'password[0]', '')} ${_.get(json, 'username[0]', '')}`
Upvotes: 0
Reputation: 23705
Actually there is tc39 proposal on that: optional chaining. After it is live it would be as easy as
const message = `Error message: ${json?.email?.[0] || ''} ${json?.password?.[0] || ''} ${json?.username?.[0] || ''}`
"Stage 1" means "it seems to be on the way to be discussed". You can use such a syntax that with help of Babel.
Otherwise(no Babel) you better use helper like lodash's _.get or write your own version. Why don't use ternary operator? Because of its bad readability.
Upvotes: 3