首页 > 解决方案 > 将枚举数转换为字符串

问题描述

我有一个枚举文件,其中我为 PaymentTypes 定义了一个对象:

export enum PaymentTypes {
   Invoice = 1,
   CreditCard = 2,
   PrePayment = 3,
}

现在,当我从我的数据库中以数组形式接收数据时,我也会以数字形式接收 PaymentType:

 order:
    [
        { "id": 0, "name": "Available", "PaymentType": 1 },
        { "id": 1, "name": "Ready", "PaymentType": 3 },
        { "id": 2, "name": "Started", "PaymentType": 2 }
    ];

现在我的问题是,如何过滤掉数组中的每种支付类型并将数字转换为枚举文件中定义的字符串,以便我可以使用这些数据将其显示给前端的用户?

所以我有这样的东西可以使用:

orderFiltered:
        [
            { "id": 0, "name": "Available", "PaymentType": "Invoice" },
            { "id": 1, "name": "Ready", "PaymentType": "PrePayment" },
            { "id": 2, "name": "Started", "PaymentType": "CreditCard" }
        ];

标签: javascripttypescriptenums

解决方案


您可以使用map创建一个新的对象数组,其中包含原始数据和枚举成员的名称,您可以使用PaymentTypes[PaymentType]

let order = [
    { "id": 0, "name": "Available", "PaymentType": 1 },
    { "id": 1, "name": "Ready", "PaymentType": 3 },
    { "id": 2, "name": "Started", "PaymentType": 2 }
];

enum PaymentTypes {
   Invoice = 1,
   CreditCard = 2,
   PrePayment = 3,
}
let orderFiltered = order.map(o => Object.assign({}, o, { PaymentTypeDisplayName: PaymentTypes[o.PaymentType] }));
console.log(orderFiltered);

不过需要注意的一点是,使用枚举成员名称作为显示可能不是最友好的使用体验。


推荐阅读