简体   繁体   English

TypeScript 枚举到 object 数组

[英]TypeScript enum to object array

I have an enum defined this way:我有一个这样定义的枚举:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

However, I'd like it to be represented as an object array/list from our API like below:但是,我希望将它表示为我们的 API 中的 object 数组/列表,如下所示:

[{id: 1, name: 'Percentage'}, 
 {id: 2, name: 'Numeric Target'},
 {id: 3, name: 'Completed Tasks'},
 {id: 4, name: 'Average Milestone Progress'},
 {id: 5, name: 'Not Measured'}]

Is there are easy and native way to do this or do I have to build a function that casts the enum to both an int and a string, and build the objects into an array?是否有简单的本机方法来执行此操作,或者我是否必须构建一个 function 将枚举同时转换为 int 和字符串,并将对象构建到数组中?

A tricky bit is that TypeScript will 'double' map the enum in the emitted object, so it can be accessed both by key and value.一个棘手的问题是 TypeScript 将“双倍”映射发出的对象中的枚举,因此可以通过键和值访问它。

enum MyEnum {
    Part1 = 0,
    Part2 = 1
}

will be emitted as将被发射为

{
   Part1: 0,
   Part2: 1,
   0: 'Part1',
   1: 'Part2'
}

So you should filter the object first before mapping.所以你应该在映射之前先过滤对象。 So @Diullei 's solution has the right answer.所以@Diullei 的解决方案有正确的答案。 Here is my implementation:这是我的实现:

// Helper
const StringIsNumber = value => isNaN(Number(value)) === false;

// Turn enum into array
function ToArray(enumme) {
    return Object.keys(enumme)
        .filter(StringIsNumber)
        .map(key => enumme[key]);
}

Use it like this:像这样使用它:

export enum GoalProgressMeasurements {
    Percentage,
    Numeric_Target,
    Completed_Tasks,
    Average_Milestone_Progress,
    Not_Measured
}

console.log(ToArray(GoalProgressMeasurements));

If you are using ES8如果您使用的是 ES8

For this case only it will work perfectly fine.对于这种情况,它只会工作得很好。 It will give you value array of the given enum .它将为您提供给定enum 的值数组。

enum Colors {
  WHITE = 0,
  BLACK = 1,
  BLUE = 3
}

const colorValueArray = Object.values(Colors); //[ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ]

You will get colorValueArray like this [ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ] .你会得到这样的colorValueArray [ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ] All the keys will be in first half of the array and all the values in second half.所有的键都在数组的前半部分,所有的值在后半部分。

Even this kind of enum will work fine即使这种枚举也能正常工作

enum Operation {
    READ,
    WRITE,
    EXECUTE
}

But this solution will not work for Heterogeneous enums like this但是这个解决方案不适用于像这样的异构枚举

enum BooleanLikeHeterogeneousEnum {
  No = 0,
  Yes = "YES",
}

Enums are real objects that exist at runtime.枚举是在运行时存在的真实对象。 So you are able to reverse the mapping doing something like this:因此,您可以执行以下操作来反转映射:

let value = GoalProgressMeasurements.Not_Measured;
console.log(GoalProgressMeasurements[value]);
// => Not_Measured

Based on that you can use the following code:基于此,您可以使用以下代码:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

let map: {id: number; name: string}[] = [];

for(var n in GoalProgressMeasurements) {
    if (typeof GoalProgressMeasurements[n] === 'number') {
        map.push({id: <any>GoalProgressMeasurements[n], name: n});
    }
}

console.log(map);

Reference: https://www.typescriptlang.org/docs/handbook/enums.html参考: https : //www.typescriptlang.org/docs/handbook/enums.html

简单地说,这将返回一个枚举值数组:

 Object.values(myEnum);

Easy Solution.简单的解决方案。 You can use the following function to convert your Enum to an array of objects.您可以使用以下函数将 Enum 转换为对象数组。

 buildGoalProgressMeasurementsArray(): Object[] {

    return Object.keys(GoalProgressMeasurements)
              .map(key => ({ id: GoalProgressMeasurements[key], name: key }))
 }

If you needed to strip that underscore off, we could use regex as follows:如果你需要去掉下划线,我们可以使用正则表达式如下:

buildGoalProgressMeasurementsArray(): Object[] {

    return Object.keys(GoalProgressMeasurements)
              .map(key => ({ id: GoalProgressMeasurements[key], name: key.replace(/_/g, ' ') }))
 }

I use我用

Object.entries(GoalProgressMeasurement).filter(e => !isNaN(e[0]as any)).map(e => ({ name: e[1], id: e[0] }));

A simple 1 line that does the job.一个简单的 1 行就可以完成这项工作。

It does the job in 3 simple steps它通过 3 个简单的步骤完成工作
- Loads the combination of keys & values using Object.entries . - 使用Object.entries加载键和值的组合。
- Filters out the non numbers (since typescript generates the values for reverse lookup). - 过滤掉非数字(因为打字稿生成反向查找的值)。
- Then we map it to the array object we like. - 然后我们将它映射到我们喜欢的数组对象。

class EnumHelpers {

    static getNamesAndValues<T extends number>(e: any) {
        return EnumHelpers.getNames(e).map(n => ({ name: n, value: e[n] as T }));
    }

    static getNames(e: any) {
        return EnumHelpers.getObjValues(e).filter(v => typeof v === 'string') as string[];
    }

    static getValues<T extends number>(e: any) {
        return EnumHelpers.getObjValues(e).filter(v => typeof v === 'number') as T[];
    }

    static getSelectList<T extends number, U>(e: any, stringConverter: (arg: U) => string) {
        const selectList = new Map<T, string>();
        this.getValues(e).forEach(val => selectList.set(val as T, stringConverter(val as unknown as U)));
        return selectList;
    }

    static getSelectListAsArray<T extends number, U>(e: any, stringConverter: (arg: U) => string) {
        return Array.from(this.getSelectList(e, stringConverter), value => ({ value: value[0] as T, presentation: value[1] }));
    }

    private static getObjValues(e: any): (number | string)[] {
        return Object.keys(e).map(k => e[k]);
    }
}

Thanks to polkovnikov.ph I was finally able to find a solution that would work for most of the use-cases.感谢polkovnikov.ph,我终于找到了适用于大多数用例的解决方案。

Valid solution for the question问题的有效解决方案

type Descripted<T> = {
    [K in keyof T]: {
        readonly id: T[K];
        readonly description: string;
    }
}[keyof T]

/**
 * Helper to produce an array of enum descriptors.
 * @param enumeration Enumeration object.
 * @param separatorRegex Regex that would catch the separator in your enum key.
 */
export function enumToDescriptedArray<T>(enumeration: T, separatorRegex: RegExp = /_/g): Descripted<T>[] {
    return (Object.keys(enumeration) as Array<keyof T>)
        .filter(key => isNaN(Number(key)))
        .filter(key => typeof enumeration[key] === "number" || typeof enumeration[key] === "string")
        .map(key => ({
            id: enumeration[key],
            description: String(key).replace(separatorRegex, ' '),
        }));
}

Example:例子:


export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

console.log(enumToDescriptedArray(GoalProgressMeasurements))
// Produces:
/*
[
    {id: 1, description: "Percentage"},
    {id: 2, description: "Numeric Target"},
    {id: 3, description: "Completed Tasks"},
    {id: 4, description: "Average Milestone Progress"},
    {id: 5, description: "Not Measured"}
]
*/

Also, there's a useful util function I use to map the enumeration object to an array of available values it has:此外,我使用一个有用的 util 函数将枚举对象映射到它具有的可用值数组:

The mapper映射器

type NonFunctional<T> = T extends Function ? never : T;

/**
 * Helper to produce an array of enum values.
 * @param enumeration Enumeration object.
 */
export function enumToArray<T>(enumeration: T): NonFunctional<T[keyof T]>[] {
    return Object.keys(enumeration)
        .filter(key => isNaN(Number(key)))
        .map(key => enumeration[key])
        .filter(val => typeof val === "number" || typeof val === "string");
}

Working use-cases工作用例

  • Numeric enum数字枚举
enum Colors1 {
    WHITE = 0,
    BLACK = 1
}
console.log(Object.values(Colors1)); // ['WHITE', 'BLACK', 0, 1]
console.log(enumToArray(Colors1));   // [0, 1]
  • String enum字符串枚举
enum Colors2 {
    WHITE = "white",
    BLACK = "black"
}
console.log(Object.values(Colors2)); // ['white', 'black']
console.log(enumToArray(Colors2));   // ['white', 'black']
  • Heterogenous enum异构枚举
enum Colors4 {
    WHITE = "white",
    BLACK = 0
}
console.log(Object.values(Colors4)); // ["BLACK", "white", 0]
console.log(enumToArray(Colors4));   // ["white", 0]
  • Enum merged with a namespace with exported functions枚举与具有导出函数的命名空间合并

enum Colors3 {
    WHITE = "white",
    BLACK = "black"
}
namespace Colors3 {
    export function fun() {}
}
console.log(Object.values(Colors3)); // ['white', 'black', Function]
console.log(enumToArray(Colors3));   // ['white', 'black']

I didn't like any of the above answers because none of them correctly handle the mixture of strings/numbers that can be values in TypeScript enums.我不喜欢上述任何一个答案,因为它们都没有正确处理可以是 TypeScript 枚举中的值的字符串/数字的混合。

The following function follows the semantics of TypeScript enums to give a proper Map of keys to values.以下函数遵循 TypeScript 枚举的语义,以提供适当的键值映射。 From there, getting an array of objects or just the keys or just the values is trivial.从那里,获取对象数组或仅键或仅值是微不足道的。

/**
 * Converts the given enum to a map of the keys to the values.
 * @param enumeration The enum to convert to a map.
 */
function enumToMap(enumeration: any): Map<string, string | number> {
  const map = new Map<string, string | number>();
  for (let key in enumeration) {
      //TypeScript does not allow enum keys to be numeric
      if (!isNaN(Number(key))) continue;

      const val = enumeration[key] as string | number;

      //TypeScript does not allow enum value to be null or undefined
      if (val !== undefined && val !== null)
          map.set(key, val);
  }

  return map;
}

Example Usage:示例用法:

enum Dog {
    Rover = 1,
    Lassie = "Collie",
    Fido = 3,
    Cody = "Mutt",
}

let map = enumToMap(Dog); //Map of keys to values

let objs = Array.from(map.entries()).map(m => ({id: m[1], name: m[0]})); //Objects as asked for in OP
let entries = Array.from(map.entries()); //Array of each entry
let keys = Array.from(map.keys()); //An array of keys
let values = Array.from(map.values()); //An array of values

I'll also point out that the OP is thinking of enums backwards.我还要指出,OP 正在向后考虑枚举。 The "key" in the enum is technically on the left hand side and the value is on the right hand side.枚举中的“键”在技术上位于左侧,而值位于右侧。 TypeScript allows you to repeat the values on the RHS as much as you'd like. TypeScript 允许您根据需要重复 RHS 上的值。

First we get an array of keys for this enum.首先,我们获得此枚举的键数组。 Then, using the map () function, we convert the data to the desired format.然后,使用 map() 函数,我们将数据转换为所需的格式。 id is obtained from the key, name is obtained from enum by the same key. id 是从key 中获取的,name 是通过相同的key 从enum 中获取的。

const converted = Object.keys(GoalProgressMeasurements).map(key => {
        return {
            id: GoalProgressMeasurements[key],
            name: key,
        };
    });

 enum GoalProgressMeasurements { Percentage = 1, Numeric_Target = 2, Completed_Tasks = 3, Average_Milestone_Progress = 4, Not_Measured = 5 } const array = [] for (const [key, value] of Object.entries(GoalProgressMeasurements)) { if (!Number.isNaN(Number(key))) { continue; } array.push({ id: value, name: key.replace('_', '') }); } console.log(array);

I would like to discourage using TS Enums in cases where list of enum entries is required.在需要枚举条目列表的情况下,我不鼓励使用 TS 枚举。

In runtime Enum is implemented as object, but it works as you expect only in this case:在运行时枚举被实现为 object,但它仅在这种情况下按预期工作:

enum X {
  Z = 'z',
  F = 'f'
};

console.log(Object.values(X))
console.log(Object.keys(X))
>>>
[LOG]: ["z", "f"] 
[LOG]: ["Z", "F"] 

In this case it works with a trap (TS lets you to access value by it's numeric value):在这种情况下,它与陷阱一起使用(TS 允许您通过它的数值访问值):

enum X {
  Z,
  F
};

console.log(Object.values(X))
console.log(Object.keys(X))
>>>
[LOG]: ["Z", "F", 0, 1] 
[LOG]: ["0", "1", "Z", "F"] 

So any function you write to loop over Enum will work/fail according to Enum definition.因此,根据枚举定义,您编写的任何 function 都将在枚举上循环工作/失败。 Which is... not good.这是...不好。

My conclusion : Enum was not designed to be used as an object. Use const instead of enum in case you need to access keys and values collections:我的结论:Enum 并非设计为用作 object。如果您需要访问键和值 collections,请使用const而不是enum

const Enumed = {
    X: 1,
    Y: 2
}

Typescript will control existence of object keys and you will be able to do Object.keys , etc. in safe and consistent way. Typescript 将控制 object 密钥的存在,您将能够以安全一致的方式执行Object.keys等操作。

export function enumKeys(E: any): string[] {
    return Object.keys(E).filter(k => isNaN(Number(k)));
}

export function enumValues(E: any): string[] | number[] {
    return enumKeys(E).map(k => E[k as any]);
}

Works with both:适用于:

enum TestA {
    RED = "red",
    BLUE = "blue"
}

enum TestB {
    ONE = 1,
    TWO = 2
}

There is a simple solution, So when you run Object.keys(Enum) that gonna give you a Array of Values and Keys, in first slice Values and in the second one keys, so why we don't just return the second slice, this code below works for me.有一个简单的解决方案,所以当你运行Object.keys(Enum) ,它会给你一个值和键的数组,在第一个切片值和第二个键中,那么为什么我们不只返回第二个切片,下面的这段代码对我有用。

enum Enum {
   ONE,
   TWO,
   THREE,
   FOUR,
   FIVE,
   SIX,
   SEVEN
}
const keys = Object.keys(Enum); 
console.log(keys.slice(keys.length / 2));
function enumKeys(_enum) {
  const entries = Object.entries(_enum).filter(e => !isNaN(Number(e[0])));
  if (!entries.length) {
    // enum has string values so we can use Object.keys
    return Object.keys(_enum);
  }
  return entries.map(e => e[1]);
}

TS: TS:

works ONLY with short (<10 elements) enum仅适用于短(<10 个元素)枚举

const keys = Object.keys(Enum).filter((el: string) => el.length > 1)
console.log(keys)
  1. Object.keys() will return an array with ['0', '1', '2', 'enumElement1', 'enumElement2', enumElement3'] Object.keys() 将返回一个包含 ['0', '1', '2', 'enumElement1', 'enumElement2', enumElement3'] 的数组
  2. filter() takes every element and check its length (because of string) and excludes all numbers from resulting array filter() 获取每个元素并检查其长度(因为字符串)并从结果数组中排除所有数字

Yet another approach using ES8 Object.entries另一种使用ES8 Object.entries 的方法

export enum Weeks {  
    MONDAY = 1,  
    TUESDAY= 2,  
    WEDNESDAY = 3,  
    THURSDAY = 4,  
    FRIDAY = 5,  
    SATURDAY=6,  
    SUNDAY=7,  
}


function convertEnumToArray(){
   const arrayObjects = []            
     // Retrieve key and values using Object.entries() method. 
     for (const [propertyKey, propertyValue] of Object.entries(Weeks)) { 

      // Ignore keys that are not numbers
      if (!Number.isNaN(Number(propertyKey))) {  
        continue;  
      }  

      // Add keys and values to array
      arrayObjects.push({ id: propertyValue, name: propertyKey });  
    }        

  console.log(arrayObjects); 
}

Will produce the following:将产生以下内容:

[ 
  { id: 1, name: 'MONDAY' },  
  { id: 2, name: 'TUESDAY' },  
  { id: 3, name: 'WEDNESDAY' },  
  { id: 4, name: 'THURSDAY' },  
  { id: 5, name: 'FRIDAY' },  
  { id: 6, name: 'SATURDAY' },  
  { id: 7, name: 'SUNDAY' } 
] 

Shamelessly stolen from this blog无耻地从这个博客窃取

I know typescript from just a few months, and the solution below worked for me.我从几个月就知道打字稿,下面的解决方案对我有用。 Hope it may help someone as well -希望它也可以帮助某人-

export enum ScheduleType {
  Basic = <any>'B',
  Consolidated = <any>'C',
}

scheduleTypes = Object.keys(ScheduleType)
.filter((k, i) => i % 2)
.map((key: any) => {
  return {
    systemValue: key,
    displayValue: ScheduleType[key],
  };
});

It gave the following result - [{displayValue: "Basic", systemValue: "B"}, {displayValue: "Consolidated", systemValue: "C"}]它给出了以下结果 - [{displayValue: "Basic", systemValue: "B"}, {displayValue: "Consolidated", systemValue: "C"}]

You can do that in this way:你可以这样做:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Milestone_Progress = 4,
    Not_Measured = 5
}

export class GoalProgressMeasurement {
    constructor(public goalProgressMeasurement: GoalProgressMeasurements, public name: string) {
    }
}

export var goalProgressMeasurements: { [key: number]: GoalProgressMeasurement } = {
    1: new GoalProgressMeasurement(GoalProgressMeasurements.Percentage, "Percentage"),
    2: new GoalProgressMeasurement(GoalProgressMeasurements.Numeric_Target, "Numeric Target"),
    3: new GoalProgressMeasurement(GoalProgressMeasurements.Completed_Tasks, "Completed Tasks"),
    4: new GoalProgressMeasurement(GoalProgressMeasurements.Average_Milestone_Progress, "Average Milestone Progress"),
    5: new GoalProgressMeasurement(GoalProgressMeasurements.Not_Measured, "Not Measured"),
}

And you can use it like this:你可以像这样使用它:

var gpm: GoalProgressMeasurement = goalProgressMeasurements[GoalProgressMeasurements.Percentage];
var gpmName: string = gpm.name;

var myProgressId: number = 1; // the value can come out of drop down selected value or from back-end , so you can imagine the way of using
var gpm2: GoalProgressMeasurement = goalProgressMeasurements[myProgressId];
var gpmName: string = gpm.name;

You can extend the GoalProgressMeasurement with additional properties of the object as you need.您可以根据需要使用对象的其他属性扩展 GoalProgressMeasurement。 I'm using this approach for every enumeration that should be an object containing more then a value.对于应该是包含多个值的对象的每个枚举,我都使用这种方法。

Since enums with Strings values differ from the ones that have number values it is better to filter nonNumbers from @user8363 solution.由于具有字符串值的枚举不同于具有数字值的枚举,因此最好从 @user8363 解决方案中过滤非数字。

Here is how you can get values from enum either strings, numbers of mixed:以下是如何从枚举字符串或混合数字中获取值的方法:

 //Helper export const StringIsNotNumber = value => isNaN(Number(value)) === true; // Turn enum into array export function enumToArray(enumme) { return Object.keys(enumme) .filter(StringIsNotNumber) .map(key => enumme[key]); }

I'm surprised in a TypeScript thread no one gave valid TypeScript function with typing supported.我在 TypeScript 线程中感到惊讶,没有人提供支持键入的有效 TypeScript 函数。 Here's variation of @user8363 solution:这是@user8363 解决方案的变体:

const isStringNumber = (value: string) => isNaN(Number(value)) === false;

function enumToArray<T extends {}>(givenEnum: T) {
  return (Object.keys(givenEnum).filter(isStringNumber) as (keyof T)[]).map(
    (key) => givenEnum[key]
  );
}

I don't think the order can be guaranteed, otherwise it would be easy enough to slice the second half of Object.entries result and map from there.我不认为可以保证顺序,否则很容易将Object.entries结果的后半部分切片并从那里映射。

The only (very minor) issues with the answers above is that上述答案的唯一(非常小的)问题是

  • there is a lot of unnecessary type conversion between string and number.字符串和数字之间有很多不必要的类型转换。
  • the entries are iterated twice when a single iteration is just as clean and effective.当单次迭代同样干净有效时,条目会被迭代两次。
type StandardEnum = { [id: string]: number | string; [nu: number]: string;}

function enumToList<T extends StandardEnum> (enm: T) : { id: number; description: string }[] {
    return Object.entries(enm).reduce((accum, kv) => {
        if (typeof kv[1] === 'number') {
            accum.push({ id: kv[1], description: kv[0] })
        }
        return accum
    }, []) // if enum is huge, perhaps pre-allocate with new Array(entries.length / 2), however then push won't work, so tracking an index would also be required
}

Exemple to get enum value inside array :在数组中获取枚举值的示例:

export enum DocumentationTypeEnum {
  GDPR = 'GDPR',
  HELP = 'HELP',
  OTHER = 'OTHER',
  FOOTER = 'FOOTER'
}
const keys = Object.keys(DocumentationTypeEnum);

console.log(keys); // Output :  ["GDPR", "HELP", "OTHER", "FOOTER"]
export const isNumber = (num?: Value | null): num is number => {
  if (num === undefined || num === null) {
    return false;
  } 
  
  const number = +num;

  if (number - number !== 0) {
    // Discard Infinity and NaN
    return false;
  }

  if (number === num) {
    return true;
  }

  if (typeof num === 'string') {
    return !(number === 0 && num.trim() === '');
  }
  return false;
};

enum En  {
  ewq1 = 1,
  we2 = 'ss',
  sad = 'sad',
}

type TEnum = {
    [id: string]: number | string;
    [nu: number]: string;
}

export const getEnumValues = <T extends TEnum>(enumerable: T) =>
  Object.keys(enumerable)
    .filter((x) => !isNumber(x))
    .map((key) => enumerable[key]) as Array<T[keyof T]>

console.log(getEnumValues(En)) // [1, "ss", "sad"] 

another way is另一种方式是

export const GoalNames = {
    [GoalProgressMeasurements.Percentage] = 'Percentage',
    [GoalProgressMeasurements.Numeric_Target] = 'Numeric Target',
    [GoalProgressMeasurements.Completed_Tasks] = 'Completed Tasks',
    [GoalProgressMeasurements.Average_Milestone_Progress] = 'Average Milestone Progress',
    [GoalProgressMeasurements.Not_Measured] = 'Not Measured'
}

and you can call:你可以打电话:

const name = GoalNames[goalEnumVal];

I solved this way我是这样解决的

        const listKeys = Object.keys(TripStatus); //TripStatus is enum type
        const numOfItem = listKeys.length/2;
        for(let i=0; i<numOfItem; i++){
          this.listStatus.push({
            id: listKeys[i],
            name: listKeys[numOfItem+i]
          })
        }

只有一行:

Object.entries(GoalProgressMeasurements).map(([key, value]) => ({id: key, value: value}))

Let the enum variable be:让枚举变量为:

 enum EnumName {
      A = 1,
      B = 2
    };

Then the list is:然后列表是:

const list = Object.keys(Enum)
.filter((value => isNaN(Number(value)) === false))
      .map(key => ({ id: key, value: Enum[key] }));

The value of list will be列表的值将是

list = [ 
{ id:1 , value: A },
{ id:2 , value: B },
];
 this worked for me :

    export enum FeedBackType {
    FEEDBACK1= 'FEEDBACK1',
    FEEDBACK2= 'FEEDBACK2',
    FEEDBACK3= 'FEEDBACK3',
    }

----------------------------------------------------------------- 
    export function getTypeFeedBackList() {
    let feedbackList: FeedBackType[] = [];
    Object.keys(FeedBackType).map((key) => {
    let strEnum = key as unknown as FeedBackType;
    feedbackList.push(strEnum);
    });
    return feedbackList;
    }
---------------------------------------------------------------- 
declare this :

    public feedbackList: FeedBackType[] = [];

and after call your function in  :

    ngOnInit(): void {
    this.feedbackList = getTypeFeedBackList();
    console.log(this.feedbackList); 
    }

Happy coding ;) 

I have solved it, this way.我已经解决了它,这样。 Suppose you have an enum like below假设你有一个像下面这样的枚举

export enum UnitEnum {
  GRAM = 'gm',
  KILOGRAM = 'kg',
  LITRE = 'lt',
  CENTIMETER = 'cm',
  INCH = 'in',
  METER = 'mt',
  KILOMETER = 'km',
}

and, you have a class like this,而且,你有一个像这样的 class,

export interface Unit {
  Name: string;
  Symbol: string;
}

then you can create a function like below to map heterogenous enums to an object of certain type,然后你可以创建一个如下所示的 function 到 map 异构枚举到某种类型的 object,

export function getDefaultUnits() {
  const myUnits = Object.entries(UnitEnum).map(x => {
    return { Name: x[0], Symbol: x[1] } as Unit
  })

  console.log(myUnits);

  return myUnits;
}

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

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