Creating JavaScript classes based on JSON schemas

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?

Answer №1

If you want to simplify the process, consider designing a DynamicClass class that takes an input value and specifies a type, such as Employees, Info...

function DynamicClass (data, type) {
  this.type = type;
  // Initialization function
}
DynamicClass.prototype.xxxx = function () {}

With this setup, you can easily create the necessary classes using your data object.

fetchJSONFile(function(data){
  for(var key in data) {
    var classObj  = new DynamicClass(data[key], key);
  }
});

Answer №2

If there are only 2 keys in the returned object, you can iterate through the entries and create 2 array variables using the map method like this:

For objects with more than 2 properties, you can utilize a switch statement inside the inner 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)

If you want all objects to share the same prototype, you can create a generic constructor function or a class, and then instantiate objects from the class. If you require specific behavior for different objects, you can extend the class and use a switch statement as shown in the previous example

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)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Editable Table Component in React

I've developed a React table as shown below: const CustomTable = ({content}) => { return ( <table className="table table-bordered"> <thead> <tr> <th>Quantity</ ...

Could someone provide clarification on this particular line of Apex code for me?

I'm completely new to Oracle Apex and I could use some guidance in understanding the code snippet I came across in a tutorial about app creation. After digging around, I suspect it might be JavaScript, but I'm not entirely certain. The scenario ...

Is there a way to retrieve the HTML raw code using backticks for string interpolation in JavaScript?

I am working on a resume builder project where the HTML template file is stored in Firebase storage and retrieved using a URL. The template has been modified to include string interpolation, such as <h1>${name}</h1>. However, when I fetch the d ...

Popup confirming successful subscription to Magento newsletter

Is there a way to create a pop-up message box that appears after the user subscribes to the newsletter? "Your subscription has been confirmed [OK]" I specifically need this functionality to be implemented using JavaScript or jQuery as I want to customi ...

The function parseFloat in Javascript can be used to subtract two numbers, returning an integer value

Apologies for the inconvenience, but I could really use some assistance. I attempted to convert a string into a decimal and was successful, although I encountered an issue: number = document.getElementById("totalcost").innerHTML; //String that rep ...

The div on my webpage is not loading its content as expected when using JavaScript

I am having trouble continuously loading the content of a div from another page. Using alert worked fine, but the page data is not loading. JavaScript <script> $(document).ready(function(){ setInterval(function(){$("#loadAvailable").load("update.p ...

When a page first loads in Next.js with Firebase, the useEffect hook may return an undefined value

My component is designed to retrieve a subcollection from firestore: import { useEffect, useState } from "react"; import { db } from '../firebase/firebaseInit' import {useAuth} from '../components/AuthContextProvider' import { ...

How to Properly Parse JSON in Java?

I have a JSON array that is producing the following output: print json_decode($array); The output string looks like this: {"dbonline":true,"success":true,"action":"geturls","authorized":true, "urls":[ {"url":"http:\/\/www.namhost.com"}, ...

What techniques can I employ to ensure that withLatestFrom() effectively interacts with itself?

In my program, I have an intermediate stream that is connected to a source, but it can also trigger events from other sources (such as user input). In another part of my code, there is a derived stream that needs to compare new data from the intermediate w ...

I'm having trouble getting my if statement to function properly with a random number

I'm currently working on creating a natural disaster sequence for my game, and I'm using Math.random to simulate different outbreak scenarios. However, I've encountered an issue at the end of my code where an if statement is supposed to trig ...

Modify one specific variable within my comprehensive collection on Firebase Firestore

After clicking the button, I need to update a variable. The variable in question is "bagAmount" and it is stored in my firestore collection. Here is a link to view the Firestore Collection: Firestore Collection Currently, I am able to update one of the va ...

Is there a difference between innerHTML strings and their corresponding strings in JavaScript?

I am facing an issue with a code snippet that seems to have an unusual error. The following code is a simplified version to demonstrate the strange behavior. <html> <head> <script type = "text/javascript"> window.onload = fun ...

Using THREE.js: Finding the nearest point between two rays in a THREE.js environment

In my current project with THREE.js, I am working with two THREE.Ray objects. Both rays have an origin point represented by a Vector3 and a direction indicated by another Vector3. I am currently exploring how to determine the nearest intersection point be ...

What steps can be taken to resolve an error encountered when attempting a dynamic data POST request from the body

Whenever I attempt the post method to fetch data on Postman and store it in a local MongoDB database, I encounter an error. The error message indicates a bad request with a status code of 400. *The following is app.js: var express = require('express& ...

Modifying JavaScript object values using the Object() constructor

My background is in Groovy, which has similar syntax to JavaScript. In Groovy, I can easily copy values from one map to another like this: def myMap1 = {}; def myMap2 = {}; myMap1["key1"] = "value1"; myMap1["key2"] = "value2"; myMap1["key3"] = "value3"; ...

Storing Boolean values in MongoDB with Express JS: A Step-by-Step Guide

I am encountering an issue where a Boolean value that I am trying to store in Mongodb always returns false. Below is the schema of my database: const UserSchema = new Schema({ name: String, password: { type: String, required: true }, isAdmi ...

Ajax not functioning after submission of form

I currently have this code snippet: $('#my_form').submit(function () { setTimeout(function () { console.log('1'); $.ajax({ type: "GET", url: "/CorrectUrl/CorrectUrl", ...

Beginning the default execution right away

Currently employing jQuery. This is my code snippet: $("#input").keypress(function(event) { getConversion(); }); Is there a way to ensure that the key pressed is first added to #input before triggering the getConversion() function? ...

What is the most efficient way to automatically start the Webpack-dev-server every time a file is

Is there a way to automatically run and refresh webpack-dev-server when I am using the Atom package called AutoSave OnChange while running my application? This is my configuration for webpack-dev-server: devServer: { contentBase: './src/inde ...

Guide on obtaining GET request in a JSON formatted data file

Trying to read data from a json file using an html GET request: http://www.example.com/xxx/?id={device}&time={time}&snr={snr}&station={station}&lat={lat}&lng={lng}&rssi={rssi}&data={data}&avgSnr={avgSnr} This is the conten ...