简体   繁体   中英

looking for better way than having switch statement in array.map for javascript

looking for better way than having switch statement in array.map for javascript. Basically is there a better way to change all the values in an array given an object or something? In this case i want to abbreviate or change all the values of an array to different values given. should i use another map or another object? Javascript Es6 question I have this:

const abvDepartments = departments.map(equip => {
  switch (equip) {
    case 'service':
      return 'Svc';
      break;
    case 'help':
      return 'HLP';
      break;
    case 'contracts':
      return 'Con';
      break;
    default:
      return '';
  }
});

There's many possibilities here, but one option would be something like this:

const abvDepartments = departments.map(equip => {
  return {
    'service': 'Svc',
    'help': 'HLP',
    'contracts': 'Con'
  }[equip] || '';
});

If you'd like, and you're not doing anything else in the map, you can shorten that even further:

const abvDepartments = departments.map(equip => ({
  'service': 'Svc',
  'help': 'HLP',
  'contracts': 'Con'
}[equip] || ''));

You can keep an object like below:

const options = {'service':'Svc','help': 'HLP' }

and then:

const abvDepartments = departments.map(equip => options[equip] || "");

declare constants outside your logic and that will always be neat. Happy Coding:)

// declare constants with uppercase
const DEP_CODE = {
  'service': 'Svc',
  'help': 'HLP',
  'contracts': 'Con'
}

const abvDepartments = departments.map(equip => DEP_CODE[equip] || '' );

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