javascript - 将枚举数转换为字符串
问题描述
我有一个枚举文件,其中我为 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" }
];
解决方案
您可以使用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);
不过需要注意的一点是,使用枚举成员名称作为显示可能不是最友好的使用体验。
推荐阅读
- ios - MapBox - 淡入淡出 MGLPolygons
- asp.net-mvc - 更改每条路线的优先级只会让它们的 actionMethod 起作用
- javascript - 在javascript中分配id的正确方法
- php - 如何使用循环在许多中获取选定输入文本的值
- laravel - 用户的 Laravel 异常
- ibm-cloud - Hyperledger Composer - 链码:过早执行
- ajax - ajaxToolkid:TabContainer:单击选项卡时会显示一个框
- javascript - Javascript函数toLocaleString()Mongo DB不工作
- google-cloud-platform - 用于执行 Python 进程的 Google Cloud Tool
- javascript - 直接 url 在 vuejs 中不起作用,但路由器推送有效