//方案一:通过entries方法来实现
let p1: Person = new Person('zhangsan',18)
let map: Map<string,string|number> = new Map(Object.entries(p1))
//方案二:通过自定义解析方法
class Person {
private name: string = ''
private age: number = 0
constructor(name:string,age:number) {
this.name = name
this.age = age
}
getValueOfKey (key: string): string|number {
let value: string|number;
switch (key){
case 'name':
value = this.name
break
case 'age':
value = this.age
break
default:
value = ''
}
return value;
}
}
function transFormObjectToMap(p: Person): Map<string,string|number> {
let map: Map<string,string|number> = new Map();
Object.keys(p).forEach((key:string) => {
map.set(key, p.getValueOfKey(key));
// map.set(key, p[key]);
});
return map;
}