首页 > 解决方案 > 从 JSON 模式生成 JavaScript 类

问题描述

我有一个 JSON 文件,其中包含有关我的工作的信息和数据,如下所示:

{
"Employes":[
        {
            "id": 1,
            "fullName": "Test Test"
        }
    ],
"Infos":[
        {
            "id": 1,
            "address": "Test Test test test test",
            "employes": 1
        }
  ]
}

我想在 JS 代码上自动生成ClassesEmployesInfos为其添加一些方法。

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(),如果是新的变成新的……等等。InfosEmployes()Infos()

我想这样做,为这些类添加一些功能,例如addNew()deleteOne()....等,所有关于 CRUD 的内容。

有什么解决办法吗?

标签: javascriptjson

解决方案


如果返回的对象只有 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)


推荐阅读