简体   繁体   English

将枚举转换为具有值的 object

[英]Convert enum to object with value

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甚至不知道从哪里开始我在 typescript 还很新手

The full expected output of actions should be:完整的预期 output actions应该是:

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

you can get the enum strings from Object.values method then iterate and concatenate as you want.您可以从Object.values方法获取枚举字符串,然后根据需要进行迭代和连接。

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

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 TS游乐场: https://tsplay.dev/WG6bkm

Wrote a simple function to do this.写了一个简单的 function 来做到这一点。

function mixEnumsToObject(e1: any, e2: any) {
  const keys1: string[] = Object.keys(e1).filter((key) => isNaN(Number(key)));
  const keys2: string[] = Object.keys(e2).filter((key) => isNaN(Number(key)));
  const mixEnumMap = new Map();

  keys1.forEach((key1) => {
    const valueObject = new Map();
    keys2.forEach((key2) => {
      valueObject.set(key2, key1 + key2);
    });
    mixEnumMap.set(key1, valueObject);
  });
  return mixEnumMap;
}

const mixedEnumObject = mixEnumsToObject(ActionTypes, RequestTypes);
console.log(mixedEnumObject);

Here's a type-safe functional solution that accepts two string enums as parameters (so you can reuse it for other cases):这是一个类型安全的功能解决方案,它接受两个字符串枚举作为参数(因此您可以在其他情况下重用它):

TS Playground link TS Playground 链接

type StringEnum = Record<string, string>;

type NestedCombinedStringEnum<
  P extends StringEnum,
  C extends StringEnum,
> = {
  [KP in keyof P]: {
    [KC in keyof C]: KP extends string ? KC extends string ? `${KP}${KC}` : never : never;
  };
};

function nestAndCombineStringEnums <
  P extends StringEnum,
  C extends StringEnum,
>(enumParent: P, enumChild: C): NestedCombinedStringEnum<P, C> {
  const result: any = {};

  for (const keyP of Object.keys(enumParent)) {
    result[keyP] = {};
    for (const keyC of Object.keys(enumChild)) {
      result[keyP][keyC] = `${keyP}${keyC}`;
    }
  }

  return result;
}

// Use:

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

enum RequestType {
  Request = 'Request',
  Success = 'Success',
  Failure = 'Failure',
}

const actions = nestAndCombineStringEnums(ActionType, RequestType);
console.log(actions.Create.Success); // "CreateSuccess"
console.log(actions); // the expected result object in your question

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM