Home > OS >  Multiple property loop object literal with enum in Javascript / Typescript
Multiple property loop object literal with enum in Javascript / Typescript

Time:12-28

Is there any way to loop inside my object literal where key and value are different enums for each?

For ex: below is the function that performs checking the type of received product, but there are several conditions. How to shorten and write more elegantly?

export enum ProductType {
  CreditCard = 'credit-card',
  PersonalLoan = 'personal-loan',
  RealStateFinancing = 'real-state-financing',
  AutoLoan = 'auto-loan',
  BankAccount = 'bank-account',
  BusinessLoan = 'business-loan',
  Broker = 'broker',
  CardMachine = 'card-machine',
  CryptoBroker = 'crypto-broker',
}
export enum ProductTypeSlugEndpointApi {
  CreditCard = 'cartoes-de-credito',
  PersonalLoan = 'emprestimos',
  RealStateFinancing = 'financiamentos-imobiliarios',
  AutoLoan = 'financiamentos-veiculos',
  BankAccount = 'contas',
  BusinessLoan = 'emprestimos-pjs',
  Broker = 'corretoras',
  CardMachine = 'maquinas-cartoes',
  CryptoBroker = 'corretoras-criptomoedas',
function MappingProductTypeToEndpointApi(type: ProductType) {
  const endpoints = {
    [ProductType.CreditCard]: ProductTypeSlugEndpointApi.CreditCard,
    [ProductType.PersonalLoan]: ProductTypeSlugEndpointApi.PersonalLoan,
    [ProductType.RealStateFinancing]:
      ProductTypeSlugEndpointApi.RealStateFinancing,
    [ProductType.AutoLoan]: ProductTypeSlugEndpointApi.AutoLoan,
    [ProductType.BankAccount]: ProductTypeSlugEndpointApi.BankAccount,
    [ProductType.BusinessLoan]: ProductTypeSlugEndpointApi.BusinessLoan,
    [ProductType.Broker]: ProductTypeSlugEndpointApi.Broker,
    [ProductType.CardMachine]: ProductTypeSlugEndpointApi.CardMachine,
    [ProductType.CryptoBroker]: ProductTypeSlugEndpointApi.CryptoBroker,
  }

  return endpoints[type] || ProductTypeSlugEndpointApi.Default
}

CodePudding user response:

change your enum for object, and keyof typeof does the trick :

    const Product = {
      CreditCard : 'credit-card',
      PersonalLoan : 'personal-loan',
      NotInEndPoints:"notinendpoints"
    } as const
    
    const EndPoints = {
      CreditCard : 'cartoes-de-credito',
      PersonalLoan: 'emprestimos',
        Default:'Default'
    } as const
    
    type TProduct = keyof typeof Product
    type TEndPoints = keyof typeof EndPoints
    
    function newMapp(type :  TProduct)
{
    return Object.keys(EndPoints).includes(type)? EndPoints[type]: EndPoints["Default"]
}

    console.log(newMapp("CreditCard")) // returns "cartoes-de-credito" 
    console.log(newMapp("NotInEndPoints")) //returns "Default"
  • Related