我正在使用带有目标ES5的TypeScript 2.2.1
我有几个枚举如下
enum PermissionLevel {
ACCOUNT_OWN,
ACCOUNT_OTHER,
USER_OWN
}
enum Permission {
ACCOUNT_CREATE,
USER_CREATE
}
我有一个输入JSON,如下所示
{
"ACCOUNT_OWN": [
"USER_CREATE",
"ACCOUNT_CREATE"
],
"ACCOUNT_OTHER": [
"USER_CREATE"
]
}
我想将此输入存储为Map<Permission, Array<PermissionLevel>>
以下是我的代码
// assume authJson is the input and is a valid JSON.
this.userPermissions = new Map<Permission, Array<PermissionLevel>>();
for (let [level, permissions] of Object.entries(authJson)) {
let newLevel: PermissionLevel = <any>PermissionLevel[level];
for (let perm of permissions) {
let newPermission: Permission = <any>Permission[perm];
if (this.userPermissions.get(newPermission)) {
this.userPermissions.set(newPermission, this.userPermissions.get(newPermission).concat(newLevel));
} else {
this.userPermissions.set(newPermission, new Array<PermissionLevel>().concat(newLevel));
}
}
}
console.log(JSON.stringify(this.userPermissions));
最后一个语句的输出是空的:(。不知道我在这里做错了什么。
更新:我刚发现下面有运行时错误
EXCEPTION: Uncaught (in promise): ReferenceError: PermissionLevel is not defined
这是一个TS小提琴 - https://jsfiddle.net/hrwyc6zv/1/
答案 0 :(得分:2)
javascript中的地图对象不是JSON。因此,JSON.stringify不会显示其实际内容。
Firefox中的小测试:
var x = new Map()
x.set('a','b')
-> Map { a: "b" }
JSON.stringify(x)
-> "{}"