How can you retrieve JavaScript Objects with inheritance from a JSON file?

Currently, I am looking to enhance my knowledge of JavaScript, particularly in the area of object inheritance. To practice this concept, I have decided to create a client for an API. This API provides a JSON object containing lists of objects that I aim to convert into lists of JavaScript objects with inheritance capabilities (to later add common functions to the Parent object).

Below is a simplified example of my current approach:

json=JSON.parse('{"lista":[{"one":"","two":""},{"one":"","two":""}],"listb":[{"one":"","three":""},{"one":"","three":""}]}')


function Parent(parent) {
    this.one = parent.one;
}

function A(a) {
    Parent.call(this,a);
    this.two = a.two;
}

A.prototype = Object.create(Parent.prototype);
A.prototype.constructor = A;

function B(b) {
    Parent.call(this,b);
    this.three = b.three;
}

B.prototype = Object.create(Parent.prototype);
B.prototype.constructor = B;

function Collection(collection) {
    this.lista = (typeof collection.lista !== "undefined" ? collection.lista.map(function (a) {
        return new A(a)
    }) : undefined);
    this.listb = (typeof collection.listb !== "undefined" ? collection.listb.map(function (b) {
        return new B(b)
    }) : undefined);
}

collection=new Collection(json);

Is there a more efficient method to generate JavaScript objects with inheritance from JSON?

Answer №1

Utilizing the JSON.parse method with a receiver function can be done in the following way:

json=JSON.parse('{"lista":[{"one":"","two":""},{"one":"","two":""}],"listb":[{"one":"","three":""},{"one":"","three":""}]',
    function(k,v){
        if(k === "lista") return v.map(function(a){return new A(a);});
        if(k === "listb") return v.map(function(a){return new B(a);});
        return v;
    })

In this situation, the json object consists of two fields where the field lista is an array of A objects and listb is an array of B objects.

Answer №2

It seems like your background is rooted in the C++/C#/Java realm :)

In JavaScript, you can implement inheritance as shown in your code snippet; however, it may just introduce unnecessary complexity without any real benefits.

Typically, when dealing with JSON input like in your example, JavaScript developers prefer to work directly with the objects themselves.

var collection={};
collection.lista = json.lista;
collection.listb = json.listb;

Overall, your approach to inheritance is perfectly acceptable.

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

Angular sends a blank object to the server

Utilizing angular along with spring boot 2 has presented a challenge for me. Each time I attempt to send a POST request, spring validation messages pop up indicating that my fields cannot be empty or null. Here is the form structure of my POST request: < ...

Saving files in ElasticSearch with a generic JsonNode using the Spring Data framework

I have a requirement to store diverse json payload data in an Elasticsearch index using Spring Data. To achieve this, I am utilizing the following entity structure: @Document(indexName = "message") public class Message { @Id ...

How can I use JavaScript to sort through an array and organize the data into groups?

Below is an array that I currently have: Status=["active","inactive","pending","active","completed","cancelled","active","completed"] I am looking to achieve the following result: StatusInfo=["active":3,"inactive":2,"pending":1, "completed":2, "cancelle ...

Troubleshooting React's failure to start with node.js running behind an Nginx Reverse Proxy

This is my first attempt at setting up a Node.js server in production (other than one Meteor server), and I've run into a problem that I can't figure out on my own. I have built an application using React. Here is the server code: // Imports va ...

What could be causing my ASP.Net MVC script bundles to load on every page view?

I'm a bit puzzled. The _layout.cshtml page I have below contains several bundles of .css and .js files. Upon the initial site load, each file in the bundles is processed, which makes sense. However, every time a new view is loaded, each line of code f ...

PHP allows for creating dropdown lists where the values are dynamically dependent on the selection of another dropdown list within the same form

Is there a way for me to implement this solution? The values in the dropdownlist are based on another dropdownlist within the same form. For example, a form with dropdownlists for car names and models of that car, along with a search button. Please take no ...

Express: ERROR_HTTP_HEADERS_ALREADY_SENT - It is not possible to set headers once they have already been sent to the client

After reviewing numerous discussions on the same topic, I am struggling to identify where I might be sending the headers initially. The stack trace provided indicates the following: It is concerning that I receive a 204 as it successfully adds to the data ...

I have the ability to effectively open a modal whenever necessary, but I struggle with closing it afterwards

I've been working on implementing a React bootstrap modal, and while I can successfully open it when needed, I'm running into issues with closing it. I'm not sure what mistake I might be making. Here's my markup: <Modal show={this. ...

Condense a lineup of names into only two rows

I have a challenge where I need to showcase a list of names separated by commas, pulled from an array in my React component. The HTML output should appear as follows: <div> <span>Liza</span>, <span>Eric</span>, <span>Mic ...

Building HTML elements using AngularJS and JavaScript

When I'm embedding HTML code within my JavaScript code, it's not recognizing that it's AngularJS code. How can I resolve this issue? I am experiencing trouble with the variables enclosed in {{}} as they are not being recognized as AngularJS ...

Issue with div element not functioning properly within table declaration on Internet Explorer

There seems to be an issue with the div tag not functioning properly inside a table definition: <table> <tr></tr> <div id="choice"><tr> <td>-------</td> <td>-------</td> <td>-------</td> &l ...

What is the solution for the error "BREAKING CHANGE: webpack < 5 used to automatically include polyfills for node.js core modules"?

I am trying to use the "web3" and "walletconnect/web3-provider" package in a Vue & Laravel 8 project. I have installed it using the npm i --save web3 @walletconnect/web3-provider command and then added the following code to import into ...

The React JSX error you encountered is due to the missing return value at the end of the arrow function

After implementing my code, I noticed the following: books.map(({ subjects, formats, title, authors, bookshelves }, index) => { subjects = subjects.join().toLowerCase(); author = authors.map(({ name }) => name).join() ...

Troubleshooting a JSON error encountered while utilizing the mongoimport tool

Currently, I am utilizing the mongoimport utility to import data from a json file into mongodb with the following command: mongoimport --db city --collection inspections ./city_inspections.json #mongo import utility The json data structure looks like this ...

Access account and refresh user document when onAuthStateChange occurs

When signing in to Firebase and updating the user doc using merge: true, an issue arises when the onAuthStateChanged listener is also active. This listener detects new logins and then reads the user doc, causing potential conflicts. Upon further inspectio ...

Utilizing various ExtJS selectors

Can Ext JS 4 support multiple selectors for event handling? I understand that in JQuery, you can achieve this by using the following syntax: $('.selector1,.selector2').click(function(){ //.. }); However, I attempted to use a similar method ...

Error encountered in a Node.js Express application: 'Error in Jade template (version 1.0+): The usage of duplicate key "id" is not permitted.'

Seeking guidance on the following issue: Within my Express app, I am providing numerous parameters to a Jade template, resulting in an error message that states: Duplicate key "id" is not allowed. (After reviewing, I have confirmed that there is no para ...

Setting a preloaded model as a property value in Three.js object

I'm fairly new to Three.js and I have a question. Is it possible to load a 3D model into Three.js and maintain that loaded model as a value in my object? The issue is, when I try to do this, I encounter a problem where I can't access this.instanc ...

Implementing CKEditor instances within AngularJS Controller scopes

Greetings everyone, Recently, I have been exploring Angular JS. Everything is going smoothly - my controllers, services, and so on. However, when attempting to make a Div editable that is within the ng-controller, the ckeditor toolbar fails to appear. On ...

Having trouble getting the jQuery AJAX post syntax to work properly

I am trying to send a post json value to another page using AJAX. However, when I include the "json" parameter in my POST request, the JavaScript code stops working. If I remove the "json" parameter, it works fine. I am still learning jQuery so any help ...