简体   繁体   中英

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' "

For readability use a shorter variable name to store the value. Then, since you are returning the input value when it matches one of the styles, you can put the styles into an array, and then you can use Array.includes to test them all at once:

button_styles = ['primary-flat', 'secondary-flat', 'tertiary-flat', 'primary-animated', 'secondary-animated', 'tertiary-animated' ];

promo_button_style = data_items.attributes.promo_banner.promo_join_button_style;

button_styles.includes(promo_button_style) ? promo_button_style : 'error'

Note that for large arrays a Set (with has ) would be more efficient:

button_styles = new Set(['primary-flat', 'secondary-flat', ...])

button_styles.has(promo_button_style) ? promo_button_style : 'error'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM