javascript - 转换为 JSON 时对象属性消失

标签 javascript json typescript

这是我的类(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]);

我明白了:

enter image description here

在我的应用程序中,我需要将患者转换为 JSON,以便通过拖放来移动它:

let thisIsNotFine=JSON.stringify(this.patientService.patients[0]);

问题来了。当我将它转换回 JS 对象并打印它时,

console.log(JSON.parse(thisIsNotFine));

我明白了:

enter image description here

如您所见,它不再称为 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/

相关文章:

javascript - 创建 handlebars.js 子菜单

javascript - 获取 jQuery 对话框中的底层元素

Python 请求仅返回 1 个元素

arrays - Swift:如何在 TableView 内的 CollectionView 中显示解析的 JSON 数据?

c# - 如何解析这个 JSON

javascript - 用于从字符串创建 JSX 元素的正确 TypeScript 类型

javascript - attr.checked 不适用于动态添加的元素

javascript - 如何将新元素附加到哈希中的相同键

angularjs - 模块 'angular' 没有导出成员 'material'

javascript - 如何在连接 JavaScript 句子时添加空格