Tips for associating JSON data with a specific class

I have utilized Babel to create an ES6 class and now I am looking for a way to map JSON data from a server to this ES6 class.
Is there a commonly used method to accomplish this task?

User.js

export default class User {
  constructor() {
    this.firstName;
    this.lastName;
    this.sex;
  }
}

app.js

import User from "./classes/User";

var data = JSON.parse(req.responseText);
console.log(data.firstname); //Bob
//should I set the data one by one?

Answer №1

To incorporate the JSON object into this, I would utilize Object.assign in the following manner:

class Person {
  name;
  age;
  gender;

  constructor(info) {
    Object.assign(this, info);
//  ^^^^^^^^^^^^^^^^^^^^^^^
  }
}

var info = JSON.parse(request.responseText);
new Person(info);

Answer №2

If you're looking to effortlessly map all JSON data to a class, consider utilizing the npm package https://www.npmjs.com/package/class-converter. This handy tool simplifies the process, as demonstrated below:

import { property, toClass } from 'class-convert';

class PersonModel {
  @property('i')
  id: number;

  @property()
  name: string;
}

const personData = {
  i: 1234,
  name: 'John Doe',
};

// Utilize the toClass method to convert plain objects to a specific class
const personModel = toClass(personData, PersonModel);
// The converted class will resemble:
{
  id: 1234,
  name: 'John Doe',
}

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

Creating a graph in a hybrid application: a step-by-step guide

As a newcomer to hybrid technology, I am currently delving into the realm of ionic framework, angular js, and phone gap. My main challenge lies in creating graphs. Can anyone offer suggestions on how to create a graph, be it a line or pie graph? Thank you ...

When utilizing webpack in Angular 5, the :host selector does not get converted into a component entity

Initially, I set up Angular with webpack following the configuration in this guide, including configuring webpack sass-loader. Everything was working smoothly until I encountered an issue today: app.component.ts @Component({ selector: 'ng-app&ap ...

div.load() results in a complete page reload

When I save form data, my goal is to load only the specific div without refreshing the entire page. However, despite using the preventDefault() command, the form still seems to be posting the whole page. I have tried adding the following code: $("#btn ...

Encountering a ReactJs and TypeScript error: "menuItems.map is not a function, issue with map method"

Greetings! I am currently working on implementing the logic of using useState and mapping an array to show only one dropdown item at a time. Below is my array structure with tags (menu name, links (to router), icon (menu icon), and if there are dropdown i ...

How can Components access variables declared in a custom Vue.js plugin?

I had developed a unique Vue js plugin to manage global variables as shown below: CustomConstants.js file: import Vue from 'vue' export default { install(Vue){ Vue.CustomConstants = { APP_VERSION: '2.1.0' ...

Encountering an issue with AJAX form submission in PHP when integrating object-oriented programming principles with Sweet Alert confirmation pop-ups

I am looking to enhance my form submission process by incorporating AJAX jQuery and adding a sweet alert confirmation before submitting the form. Currently, the form functions correctly without any AJAX or JavaScript; however, I want to improve the user e ...

Calculate the combined sum and alter the values of three input fields

There are three text boxes (testbox, testbox2, testbox3) that receive values from an input field, radio button selection, and checkbox. The correct values are displayed in testbox, testbox2, testbox3. Additionally, the sum of testbox, testbox2, testbox3 n ...

Using React to inject SCSS classes on the fly

Looking for advice on the best way to dynamically insert SASS classes using React. I have a React component that takes in two props: componentId and color. These components are displayed as a list, and each time they're rendered, I want to apply the ...

Converting JSON-style data into a string with the power of node mysql

Just a quick note - I'm a total newbie in the world of web development, so I might be missing an obvious solution here. My challenge is to insert a dataset into a MySQL database using nodejs/expressjs/mysql. I've managed to establish a connecti ...

AngularJS: The dynamic setting for the stylesheet link tag initiates the request prematurely

I'm encountering a problem that is somewhat similar (although not exactly the same, so please be patient) to the one discussed in Conditionally-rendering css in html head I am dynamically loading a stylesheet using a scope variable defined at the sta ...

Exploring the Potential of Using ngIf-else Expressions in Angular 2

Here is a code snippet that I wrote: <tr *ngFor="let sample of data; let i = index" [attr.data-index]="i"> <ng-container *ngIf="sample.configuration_type == 1; then thenBlock; else elseBlock"></ng-container> <ng-template #t ...

View's list fails to reflect changes in the Model

My goal is to create a MVVM architecture using knockout.js. The script within $(document).ready(function() {...} is supposed to add a new item model.addElement("value"); - "value" to the model every 3 seconds and display it in HTML. Despite seeing changes ...

Obtain a value using a jQuery for-in loop

I have multiple items stored in a database, each item has a unique ID assigned to it which is included in a link within the href attribute. My goal is to extract the IDs from these links that are generated within a PHP while loop. I attempted to use a for ...

The Meteor update is unsuccessful on the Mongo Sub Collection and will not continue

I am currently facing an issue with updating a specific object within an array in my object based on a value. Whenever I try to add the update code, the function gets stuck at that point without proceeding further. None of the console.log calls after the u ...

Encountering a 'DiscordAPIError: Unknown interaction' error while attempting to share details about a command

As I work on a slash command to deliver information about a specific command when users type /help, I encountered an error when trying to add multiple commands: E:\v13\node_modules\discord.js\src\rest\RequestHandler.js:298 ...

Error Encountered: RSA Key Pairs Invalid Signature for JSON Web Token (JWT)

I am facing an issue with my Node.js application (version 20.5.1) regarding the verification of JSON Web Tokens (JWT) using RSA key pairs. The specific error message I am encountering is: [16:39:56.959] FATAL (26460): invalid signature err: { "type& ...

Struggling to make dynamically created SVG 'use' elements function properly

SVG offers a unique system with symbol and use where icons can be defined once and reused throughout the SVG using use. However, I am having trouble getting it to work from JavaScript. You can view an example on this JSFiddle link. When programmatically ...

What is the best way to trigger an event function again once a specific condition has been satisfied?

I'm currently working on a project where I need a sidebar to scroll at a slower rate until it reaches a specific point, and then stop scrolling once that point is reached. Below is the jQuery code I've been using: $(window).on("scroll", function ...

Is it possible to add data in MongoDB without specifying a field name?

I have a couple of queries that revolve around the same concept: If I want to insert a new 'row' in MongoDB, can I do so by specifying the order of the fields? For instance, if my collection looks like items = { { name: "John", age: "28" ...

How can I retrieve a list of dynamic dropdown/selectbox options using JavaScript and Laravel?

I am facing an issue with a dynamic dropdown field in my update form modal/popup within Laravel 5.2. The dropdown list works only in the first row, and when I add more dropdowns, the lists do not show up because I am unsure how to implement foreach in the ...