I have a JSON file containing information and data related to my work, presented in the following format:
{
"Employees":[
{
"id": 1,
"fullName": "Test Test"
}
],
"Infos":[
{
"id": 1,
"address": "Test Test test test test",
"employees": 1
}
]
}
I am looking to automatically generate Employees
and Infos
Classes in JavaScript code, and then add some methods to them.
The function fetchJSONFile
is designed to retrieve data from a JSON file using AJAX:
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();
}
Next, I am attempting to automatically generate Classes and assign objects to them by calling the following function:
function generate(nameOfObject){
fetchJSONFile(function(data){
employees = Object.assign(new Employees(), ...data[nameOfObject]);
console.log(employees);
});
}
My goal is to dynamically assign JSON data to the respective classes, so that if it's Infos
, a new Infos()
instance is created instead of Employees()
.
I intend to enhance these classes with functions like addNew()
and deleteOne()
for CRUD operations. Are there any solutions or suggestions for achieving this?