[Vuejs]-How can i turn this code into a helper function?

3👍

You should simply have usertypeToName as array and then use find

import { USER_TYPES } from '../../constants/user';

const usertypeToName = ['client', 'supportWorker','accountManager']
// find key
const key = usertypeToName.find(v=> v === this.$route.params.userType)
// use dynamic property accessor
return key ? USER_TYPES[key] : 0

0👍

Is this what you are looking for?

## util.js

import { USER_TYPES } from '../../constants/user';

const userTypeMap = {
  client: USER_TYPES.client,
  supportWorker: USER_TYPES.supportWorker,
  accountManager: USER_TYPES.accountManager,
};

export function mapUserType(name) {
  // Fallback to 0 incase mapping does not exist
  return userTypeMap[name] || 0
}


## component.js

import { mapUserType } from './util.js'

const userType = mapUserType(this.$route.params.userType)

Leave a comment