1

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 '';
  }
});
2

3 Answers 3

3

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] || ''));
Sign up to request clarification or add additional context in comments.

2 Comments

|| '', for the default.
+1 for this. one more thing I would suggest here. as an object is a constant therefore make it const outside the method and use it inside const depCode = { 'service': 'Svc', 'help': 'HLP', 'contracts': 'Con' } const abvDepartments = departments.map(equip => depCode[equip] || '' );
3

You can keep an object like below:

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

and then :

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

Comments

0

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] || '' );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.