Search code examples
javascriptif-statementternary

Convert ternary to if/else in mapped array function


I have a ternary within a map function, that currently only switches based on one option. I need to be able to pull the "home" option and set it to "/" if the user clicks that option

const buttons = ['Home', 'Docs', 'About-Us'];
const buttonSlugs = buttons.map(button => button === 'About-Us' ? 'aboutus' : button.toLowerCase());

How can I modify the ternary to an if/else, so that the home button can be set to "/"?


Solution

  • You can use a conditional like:

    const buttons = ['Home', 'Docs', 'About-Us'];
    const buttonSlugs = buttons.map(button => {
      if (button === 'About-Us') { 
        return 'aboutus';
      }
      else if (button === 'Home') {
        return '/';
      }
      else {
        return button.toLowerCase();
      }
    });
    
    console.log(buttonSlugs);

    But this sort of approach can get ugly if you have many mappings or if you expect to add more. Another approach is to use an object of functions, each of which performs the transformation you wish for a given button:

    const buttons = ['Home', 'Docs', 'About-Us'];
    const transformations = {
      'About-Us': () => 'aboutus',
      Home: () => '/',
      Docs: button => button.toLowerCase(),
    };
    const buttonSlugs = buttons.map(btn => transformations[btn](btn));
    
    console.log(buttonSlugs);

    This is easily extensible and keeps the transformation logic out of the map.

    If you want a default action or the ability to handle missing buttons, you can check for an empty key in the transformations object before calling the retrieved function and proceed accordingly.