我想迭代一个TypeScript枚举对象,并获得每个枚举符号名称,例如: enum myEnum {entry1, entry2}

for (var entry in myEnum) { 
    // use entry's name here, e.g., "entry1"
}

当前回答

这对于基于键值的enum更有效:

enum yourEnum {
  ["First Key"] = "firstWordValue",
  ["Second Key"] = "secondWordValue"
}

Object.keys(yourEnum)[Object.values(yourEnum).findIndex(x => x === yourValue)]
// Result for passing values as yourValue
// FirstKey
// SecondKey

其他回答

如果你只搜索名称,然后迭代使用:

Object.keys(myEnum).map(key => myEnum[key]).filter(value => typeof value === 'string') as string[];

Typescript游乐场示例

enum TransactionStatus {
  SUBMITTED = 'submitted',
  APPROVED = 'approved',
  PAID = 'paid',
  CANCELLED = 'cancelled',
  DECLINED = 'declined',
  PROCESSING = 'processing',
}


let set1 = Object.entries(TransactionStatus).filter(([,value]) => value === TransactionStatus.SUBMITTED || value === TransactionStatus.CANCELLED).map(([key,]) => {
    return key
})


let set2 = Object.entries(TransactionStatus).filter(([,value]) => value === TransactionStatus.PAID || value === TransactionStatus.APPROVED).map(([key,]) => {
    return key
})

let allKeys = Object.keys(TransactionStatus)



console.log({set1,set2,allKeys})

我的Enum是这样的:

export enum UserSorting {
    SortByFullName = "Sort by FullName", 
    SortByLastname = "Sort by Lastame", 
    SortByEmail = "Sort by Email", 
    SortByRoleName = "Sort by Role", 
    SortByCreatedAt = "Sort by Creation date", 
    SortByCreatedBy = "Sort by Author", 
    SortByUpdatedAt = "Sort by Edit date", 
    SortByUpdatedBy = "Sort by Editor", 
}

这样做会返回undefined:

UserSorting[UserSorting.SortByUpdatedAt]

为了解决这个问题,我选择了另一种使用管道的方法:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'enumKey'
})
export class EnumKeyPipe implements PipeTransform {

  transform(value, args: string[] = null): any {
    let enumValue = args[0];
    var keys = Object.keys(value);
    var values = Object.values(value);
    for (var i = 0; i < keys.length; i++) {
      if (values[i] == enumValue) {
        return keys[i];
      }
    }
    return null;
    }
}

要使用它:

return this.enumKeyPipe.transform(UserSorting, [UserSorting.SortByUpdatedAt]);

这里发现的另一个有趣的解决方案是使用ES6 Map:

export enum Type {
  low,
  mid,
  high
}

export const TypeLabel = new Map<number, string>([
  [Type.low, 'Low Season'],
  [Type.mid, 'Mid Season'],
  [Type.high, 'High Season']
]);

USE

console.log(TypeLabel.get(Type.low)); // Low Season


TypeLabel.forEach((label, value) => {
  console.log(label, value);
});

// Low Season 0
// Mid Season 1
// High Season 2    

在当前的TypeScript版本1.8.9中,我使用类型化enum:

export enum Option {
    OPTION1 = <any>'this is option 1',
    OPTION2 = <any>'this is option 2'
}

与结果在这个Javascript对象:

Option = {
    "OPTION1": "this is option 1",
    "OPTION2": "this is option 2",
    "this is option 1": "OPTION1",
    "this is option 2": "OPTION2"
}

所以我必须通过键和值查询,只返回值:

let optionNames: Array<any> = [];    
for (let enumValue in Option) {
    let optionNameLength = optionNames.length;

    if (optionNameLength === 0) {
        this.optionNames.push([enumValue, Option[enumValue]]);
    } else {
        if (this.optionNames[optionNameLength - 1][1] !== enumValue) {
            this.optionNames.push([enumValue, Option[enumValue]]);
        }
    }
}

我在数组中收到选项键:

optionNames = [ "OPTION1", "OPTION2" ];