javascript - 从 JSON 模式生成 JavaScript 类
问题描述
我有一个 JSON 文件,其中包含有关我的工作的信息和数据,如下所示:
{
"Employes":[
{
"id": 1,
"fullName": "Test Test"
}
],
"Infos":[
{
"id": 1,
"address": "Test Test test test test",
"employes": 1
}
]
}
我想在 JS 代码上自动生成ClassesEmployes
并Infos
为其添加一些方法。
fetchJSONFile 是一个使用 AJAX 从 JSON 文件中获取数据的函数:
function fetchJSONFile(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('GET', 'datas.json');
httpRequest.send();
}
因此,在生成功能上,我想自动生成类并为其分配对象,我尝试这样做:
function generate(nameOfObject){
fetchJSONFile(function(data){
employes = Object.assign(new Employes(), ...data[nameOfObject]);
console.log(employes);
});
}
在这一行中,我将 JSON 对象分配给我的Employes()
类,我的问题是如何自动生成JSON 类型的分配,例如Employes()
,如果是新的变成新的……等等。Infos
Employes()
Infos()
我想这样做,为这些类添加一些功能,例如addNew()
,deleteOne()
....等,所有关于 CRUD 的内容。
有什么解决办法吗?
解决方案
如果返回的对象只有 2 个键,您可以map
通过条目创建 2 个数组变量,如下所示:
如果您有超过 2 个属性,则可以在switch
内部使用 a map
:
function Employee() { this.defaultEmployeeProp = "default" }
function Infos() { this.defaultInfosProp = "default" }
const data={"Employes":[{"id":1,"fullName":"Test Test"}],"Infos":[{"id":1,"address":"Test Test test test test","employes":1}]}
const [employees, infos] = Object.entries(data).map(([key, values]) =>
values.map(e => Object.assign(key === "Employes" ? new Employee() : new Infos(), e))
)
console.log(employees)
console.log(infos)
如果您希望所有类型的对象都具有相同的属性prototype
,那么就不需要在map
. 创建一个泛型构造函数或class
,然后创建 的实例class
。如果您想要每种类型的对象的特定行为,您始终可以extend
使用该类并使用switch
前面代码段中提到的
function GenericConstructor() {
this.default = "default"
}
GenericConstructor.prototype.commonMethod = function() {
console.log("common method called")
}
const data={"Employes":[{"id":1,"fullName":"Test Test"}],"Infos":[{"id":1,"address":"Test Test test test test","employes":1}]}
const [employees, infos] = Object.entries(data).map(([key, values]) =>
values.map(e => Object.assign(new GenericConstructor(), e))
)
console.log(employees)
console.log(infos)
推荐阅读
- chat - 如何使用 Telethon 获取聊天管理员用户
- wireless - gnuradio(-companion) 中从“采样基带信号”到 PDU 的异步转换
- r - 如何使 Autoplot.zoo 中的绘制线具有不同的颜色?如何在后台添加软网格线?
- java - 无法从 long[] 转换为 long
- javascript - 使用 azure-sb 进行并行消息处理
- windows-terminal - 如何在 Windows 终端预览中真正禁用 ctrl+shift+箭头键?
- c - 使用多个参数
- python - Python:我试图写一个文本文件,但它只是不断被清除
- arduino - 使用整数函数返回值返回指针
- vb.net - vb中的参数线程