noclist
noclist

Reputation: 1819

Simply typescript conditional expressions into ternary statements

I have the following if statement. Is this expression able to be simplified into a ternary statement? I'm having trouble figuring it out since group needs to be assigned based on the value of coverageLineId

let group;
if(coverageLineId == 1)
  group = this.medicalBenefitsGroupsView.find((x) => x.value === groupValue);
else if (coverageLineId == 2)
  group = this.dentalBenefitsGroupsView.find((x) => x.value === groupValue);
else if (coverageLineId == 3)
  group = this.visionBenefitsGroupsView.find((x) => x.value === groupValue);

Upvotes: 0

Views: 279

Answers (2)

pigrammer
pigrammer

Reputation: 3519

If you really want to make it more concise, you can do this:

let group = this[["", "medical", "dental", "vision"][coverageLineId] + "BenefitsGroupsView"].find((x) => x.value === groupValue);

However, I think I'd do this:

let view;
switch (coverageLineId) {
    case 1:
        view = this.medicalBenefitsGroupsView; break;
    case 2:
        view = this.dentalBenefitsGroupsView; break;
    case 3:
        view = this.visionBenefitsGroupsView; break;
}
let group = view.find((x) => x.value === groupValue);

Upvotes: 1

dhaker
dhaker

Reputation: 1825

You can do something like

let group;

group = coverageLineId == 1 ? this.medicalBenefitsGroupsView.find((x) => x.value === groupValue) :
        coverageLineId == 2 ? this.dentalBenefitsGroupsView.find((x) => x.value === groupValue) :
        coverageLineId == 3 ? this.visionBenefitsGroupsView.find((x) => x.value === groupValue) : undefined;

Upvotes: 1

Related Questions