I have the code which is running properly, how can i write this piece of code better
if (!this.isThis) {
return [
{ label: this.$t('profile'), value: this.acc.AccountNumber, id: 'ProfileNumber' },
]
} else {
return [
{ label: this.$t('market'), value: this.acc.label, id: 'market' },
{ label: this.$t('profile'), value: this.acc.AccountNumber, id: 'ProfileNumber' },
{ label: this.$t('account'), value: this.acc.profile, id: 'account' }
]
}
can i use some better js code to handle this, above works but there are better ways to write
CodePudding user response:
Given that they share the same middle element, you could rewrite it like this:
return [
...this.isThis ? [{ label: this.$t('market'), value: this.acc.label, id: 'market' }] : [],
{ label: this.$t('profile'), value: this.acc.AccountNumber, id: 'ProfileNumber' },
...this.isThis ? [{ label: this.$t('account'), value: this.acc.profile, id: 'account' }] : [],
]
CodePudding user response:
If you have only this if else case you can remove else :
If your condition will work then it will return ifs value
By default (else) it can return your else value without else block .
Like this
if (!this.isThis) {
return [
{ label: this.$t('profile'), value:
this.acc.AccountNumber, id:
'ProfileNumber' }
]}
return [
{ label: this.$t('market'), value: this.acc.label, id: 'market' },
{ label: this.$t('profile'), value: this.acc.AccountNumber, id: 'ProfileNumber' },
{ label: this.$t('account'), value: this.acc.profile, id: 'account' }
]
CodePudding user response:
@Andrew Parks,
Perhaps, even smaller:
return [
{ label: this.$t('profile'),
value: this.acc.AccountNumber,
id: 'ProfileNumber' },
...this.isThis ? [{ label: this.$t('market'),
value: this.acc.label,
id: 'market' },
{ label: this.$t('account'),
value: this.acc.profile,
id: 'account' }
] : [],
]
CodePudding user response:
Conditional truthy array elements can be conventionally added with short circuit and then filtered:
return [
this.isThis && { label: this.$t('market'), value: this.acc.label, id: 'market' },
{ label: this.$t('profile'), value: this.acc.AccountNumber, id: 'ProfileNumber' },
this.isThis && { label: this.$t('account'), value: this.acc.profile, id: 'account' }
].filter(Boolean)
It still may be more verbose but easier to read with conditional push
.