Search code examples
javascriptternary

I would like to ask if there's a way to shorten this ternary statement?


I would like to know the possibilities on how to shorten ternary statement here? TIA

data_items.attributes.promo_banner.promo_join_button_style === 'primary-flat' ? 'primary-flat' : data_items.attributes.promo_banner.promo_join_button_style === 'secondary-flat' ? 'secondary-flat' : data_items.attributes.promo_banner.promo_join_button_style === 'tertiary-flat' ? 'tertiary-flat' : data_items.attributes.promo_banner.promo_join_button_style === 'primary-animated' ? 'primary-animated' : data_items.attributes.promo_banner.promo_join_button_style === 'secondary-animated' ? 'secondary-animated' : data_items.attributes.promo_banner.promo_join_button_style === 'tertiary-animated' ? 'tertiary-animated' : 'error' "

Solution

  • You can do something like this:

    const dataStyle = data_items.attributes.promo_banner.promo_join_button_style;
    
    dataStyle === "primary-flat"
      ? "primary-flat"
      : dataStyle === "secondary-flat"
      ? "secondary-flat"
      : dataStyle === "tertiary-flat"
      ? "tertiary-flat"
      : dataStyle === "primary-animated"
      ? "primary-animated"
      : dataStyle === "secondary-animated"
      ? "secondary-animated"
      : dataStyle === "tertiary-animated"
      ? "tertiary-animated"
      : "error";
    

    Btw you should not use such long ternary operators. For such code try using a switch statement.