Home > database >  Convert enum to object with value
Convert enum to object with value

Time:12-03

I would like to create a helper that can return an object/enum like value so we're not repeating patterns:

enum ActionTypes {
    Find,
    Update,
    Create
}
enum RequestTypes {
    Request,
    Success,
    Failure

}

If i was starting with this enum here, I need a helper method that can convert this to the following:

const actions = createActions(ActionTypes);
// actions.Find.Request -> 'FindRequest'
// actions.Find.Success -> 'FindSuccess'

Not even sure where to begin i'm pretty novice at typescript

The full expected output of actions should be:

{
    Find: {
        Request: 'FindRequest',
        Success: 'FindSuccess',
        Failure: 'FindFailure'
    },
    Create: {
        Request: 'CreateRequest',
        Success: 'CreateSuccess',
        Failure: 'CreateFailure'
    },
    Update: {
        Request: 'UpdateRequest',
        Success: 'UpdateSuccess',
        Failure: 'UpdateFailure'
    }
}

CodePudding user response:

you can get the enum strings from Object.values method then iterate and concatenate as you want.

enum ActionTypes {
  Find,
  Update,
  Create
}
enum RequestTypes {
  Request,
  Success,
  Failure

}


function createActions(actionTypes) {


  let actionTypeStrings = Object.values(actionTypes).filter(e => typeof e == 'string');
  let requestTypeStrings = Object.values(RequestTypes).filter(e => typeof e == 'string');

  let actions = actionTypeStrings.reduce((a, c) => {

    let anAction: any = {};
    requestTypeStrings.forEach((e: any) => anAction[e] = c   e)

    a[c] = anAction;

    return a;
  }, < any > {})

  return actions;
}


const actions = createActions(ActionTypes);
console.log(actions);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This is what you can do:

enum ActionTypes {
    Find = 'Find',
    Update = 'Update',
    Create = 'Create'
}

enum RequestTypes {
    Request = 'Request',
    Success = 'Success',
    Failure  = 'Failure'

}

type combination = {
  [k in  ActionTypes]: {
    [k1 in  RequestTypes]: `${k}${k1}`
  }
}


function createActions(): combination {
  return Object.keys(ActionTypes).reduce((cum, k) => {
     cum[k] = Object.keys(RequestTypes).reduce((cum1, k1) => {
       cum1[k1] = `${k}${k1}`
       return cum1;
     }, {} as any)
     return cum;
  } , {} as any)
}


console.log(createActions().Create.Failure)
// CreateFailure

TS Playground: https://tsplay.dev/WG6bkm

  • Related