sayou
sayou

Reputation: 913

Create a JavaScript Class from a JSON Object

I have a JSON file which contains information data, and I get this data using AJAX using this function to fetch it.

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', 'database.json');
    httpRequest.send(); 
}

And I fetch it to assign it to the object of the current Class:

fetchJSONFile(function(data){ 
    employes = Object.assign(new Employes(), ...data.Employes);
    console.log(employes);
})

The data within my JSON file is this:

{

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

My question is how to generate Classes automatically of each object type from the JSON file.

Using my code like for example I want to generate Employes and Infos Classes automatically here without having to create them manually.

fetchJSONFile(function(data){ 
        employes = Object.assign(new Employes(), ...data.Employes); //Generate Classes automatically here from data type
        console.log(employes);
    })

Is there any solution?

Upvotes: 1

Views: 3437

Answers (1)

Marcell Toth
Marcell Toth

Reputation: 3688

JS does not natively have classes in the same sense as most OOP languages. You probably come from an OOP background, you should learn about JS's prototype based inheritance.

You will understand that you don't actually have to create those classes. You can achieve what (I think) you are looking for via simply writing:

fetchJSONFile(function(data){ 
        employes = data.Employes; 
        // or, if you wish to make a copy
        //employes = data.Employes.map(e => {...e})
        console.log(employes);
    })

Upvotes: 1

Related Questions