这是我的类(class):
export class Patient {
constructor(public id: number, public name: string, public location: string, public bedId: number, public severity: string,
public trajectory: number, public vitalSigns: [GraphData[]], public latestReading: GraphData[]){
}
public get getCombinedVSData(): Array<GraphData>{
let combinedVitalSigns: GraphData[] = [];
for (let data of this.vitalSigns){
combinedVitalSigns.push(data[0]);
}
return combinedVitalSigns;
}
}
当我打印一位患者时,
console.log(this.patientService.patients[0]);
我明白了:
在我的应用程序中,我需要将患者转换为 JSON,以便通过拖放来移动它:
let thisIsNotFine=JSON.stringify(this.patientService.patients[0]);
问题来了。当我将它转换回 JS 对象并打印它时,
console.log(JSON.parse(thisIsNotFine));
我明白了:
如您所见,它不再称为 Patient
在控制台中,以及 getCombinedVSData
setter/getter 消失了。
这是正常行为吗?将对象转换为 JSON 时如何保留对象上的 getter?谢谢。
最佳答案
来自JSON docs ,JSON 不能包含函数,因此您的方法不会被解析为 JSON。有效数据类型为字符串、数字、对象、数组、true、false 和 null。
以下是 json.stringify()
和 json.parse()
从对象中删除方法的示例:
var obj = {
"prop" : "value",
"method" : function( num ){
return num + 1;
}
};
var json = JSON.stringify( obj );
var new_obj = JSON.parse( json );
Object.keys( new_obj ).forEach(function(key){
console.log( key + " : " + new_obj[key] );
});
关于javascript - 转换为 JSON 时对象属性消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45219726/