What is the best way to convert objects (DTO) on the client side?

  • Typescript
  • ABP + .NET Core

Currently utilizing a grid for row insertion, specifically a component of the DevExtreme framework. Similar to other grids, it triggers onRowInserting events when records are inserted with the inserted row as a parameter. I'm in need of converting this "anonymous" object (inserted data) into my client-side DTO within this event.

onRowInserting(e) {
    let mynewrow: ItemDto = e.data; // e.data holds the inserted row
}

To gain a clearer understanding of my goal, refer to the following post:

Add rows to DevExtreme grid (angular) - model/schema

EDIT

The structure of ItemDto:

export class ItemDto implements IItemDto {
    description: string;
    note: string;
    quantity: number;
    postId: number;
    id: number;

    constructor(data?: IItemDto) {
        if (data) {
            for (var property in data) {
                if (data.hasOwnProperty(property))
                    (<any>this)[property] = (<any>data)[property];
            }
        }
    }

    init(data?: any) {
        if (data) {
            this.description = data["description"];
            this.note = data["note"];
            this.quantity = data["quantity"];
            this.postId = data["postId"];
            this.id = data["id"];
        }
    }

    static fromJS(data: any): ItemDto {
        let result = new ItemDto();
        result.init(data);
        return result;
    }

    toJSON(data?: any) {
        data = typeof data === 'object' ? data : {};
        data["description"] = this.description;
        data["note"] = this.note;
        data["quantity"] = this.quantity;
        data["postId"] = this.postId;
        data["id"] = this.id;
        return data; 
    }

    clone() {
        const json = this.toJSON();
        let result = new ItemDto();
        result.init(json);
        return result;
    }
}

export interface IItemDto {
    description: string;
    note: string;
    quantity: number;
    postId: number;
    id: number;
}

Below is the content of e.data (some columns not included since only a few fields have been added to the grid at this point).

Object {
    __KEY__: "7c2ab8-1ff6-6b53-b9d7-ba25c27"
    description: "mydescription"
    id: 32
    note: "mynote"
    postId: 4
    quantity: 2
     >  __proto__: Object { constructor; , _defineG....
}

For a visual representation of the object, refer to this image: https://i.sstatic.net/XkEB1.jpg

Uncertain about the line let mynewrow: ItemDto. Unsure if it's correct or sufficient for later use, such as passing it to the service responsible for saving the new row.

Answer №2

Have you considered using the Object.assign() method to transfer the values of the properties from your JSON response object into the desired class?

class customClass {
  property = null;
  display = function() {
    console.log(this.property);
  };
}

const jsonData = { 
  property: "hello world" 
};

const instance = Object.assign(new customClass(), jsonData);

instance.display()

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

Has Angular Material 3 implemented convenient CSS classes to handle margin, padding, flexbox, and other styling attributes?

Are there ready-to-use CSS helper classes for margin/padding, flexbox, etc. available in Angular Material 3? I've noticed that Vuetify, Tailwind, Bootstrap offer a variety of convenient helper classes (such as px-4, ma-6, mx-auto, etc.). Is there any ...

An issue has occurred: [ERR_REQUIRE_ESM] You must utilize the import statement in order to load an

These are the snippets of code I'm working with: index.ts import { MikroORM } from "@mikro-orm/core" import { __prod__ } from "./constants"; import { Post } from "./entities/Post"; import microConfig from "./mikro-o ...

How can TypeScript leverage the power of JavaScript libraries?

As a newcomer to TypeScript, I apologize if this question seems simplistic. My goal is to incorporate JavaScript libraries into a .ts file while utilizing node.js for running my program via the console. In my previous experience with JavaScript, I utilize ...

An issue has occurred: Unable to access the 'seatsavailable' property of an undefined object

Currently, I am immersed in a project involving Angular 6 and utilizing the @Input and @Output decorators. In this scenario, I have the Bookride Component functioning as the parent component with RideDetails serving as the child component. Successfully tra ...

Navigating using ViewChild in Ionic 2 Beta

I recently updated my Ionic 2 app to use Angular 2 RC1, which has been a great improvement. However, I am facing some challenges with the routing implementation. Despite following the update guide, I still encounter issues with my navigation component bein ...

What methods can be used to monitor changes made to thumbnails on the YouTube platform?

I have embarked on a project to create a Chrome extension that alters the information displayed on the thumbnails of YouTube's recommended videos. In this case, I am looking to replace the video length with the name of the channel. Imagine you are on ...

The angular-oauth2-oidc library is having issues loading the jsrsasign module

I'm currently working on upgrading a dependency in Angular for a project that was forked from: https://github.com/mgechev/angular-seed The dependency in question is located at: https://github.com/manfredsteyer/angular-oauth2-oidc. However, I'm f ...

Guide to displaying a particular component depending on the URL in Angular 5

Currently, in group-summary.component.html, this code is used: <div class="row"> <ng-container> <nol-apple-details *ngIf="isAppleRouteActivated" [someDetails]="detailsToShow" class="col-xs-12 col-md-12"></nol-apple-detai ...

Perform synchronous HTTP requests using Observables

Currently, I am working on an Angular 2 project where I need to execute multiple HTTP requests sequentially. Each request is dependent on the data received from the previous one. Is there a way to accomplish this using Observables? Here is my current app ...

Enhancing NG Style in Angular 6 using a custom function

Today, my curiosity lies in the NG Style with Angular 6. Specifically, I am seeking guidance on how to dynamically update [ngStyle] when utilizing a function to determine the value. To better illustrate my query, let me present a simplified scenario: I ha ...

Typescript claims that my object lacks certain properties that it actually has

I'm currently developing a project that follows this particular structure: interface IAuthProvider { middleware: () => void getInput: () => void } class Password implements IAuthProvider { middleware = () => {} getInput = () => {} ...

Set the array as the object attribute

Transitioning my app from AngularJs to Angular 4 has been quite a challenge. I've noticed that the type of statements I frequently used in my code are now failing in Angular 4 (TypeScript): Update: The following lines were previously used in Angular ...

Oops! Looks like there's an issue with the type error: value.forEach is

I am working on creating an update form in Angular 6 using FormArray. Below is the code snippet I have in editfrom.TS : // Initialising FormArray valueIngrident = new FormArray([]); constructor(private brandService: BrandService, private PValueInfoSe ...

Transferring data between two TypeScript files of different Angular 2 components

I have two components, Component A and Component B, which are not parent-child components but I need to pass data from Component A to Component B. Example: Component A.ts has an array of data: myData: [ {'name':'some a','email& ...

In React and TypeScript, when I pass a state as a prop, the data fails to render

Here is the useState function for managing the Data Interestingly, removing this state from the code doesn't affect rendering at all. const [cart, setCart] = useState([] as Product[]); This piece of code handles Mapping and Rendering the Data <Sin ...

Angular is utilizing esbuild for integrating ckeditor, but it seems like there is no loader configured for the ".svg"

I am currently using ckEditor and encountering an error when importing a plugin. The specific error message is: No loader is configured for ".svg" files with reference to a file named table.svg located in the node_modules directory. The versions ...

Using TypeScript in the current class, transform a class member into a string

When converting a class member name to a string, I rely on the following function. However, in the example provided, we consistently need to specify the name of the Current Component. Is there a way to adjust the export function so that it always refers ...

Scroll to reach the bottom of the page triggers an activation function

I need help figuring out how to trigger a function when the scrollbar reaches the bottom of the page. Is there a way to determine if the scroll has reached the end of the page? @HostListener("window:scroll", []) onScroll(): void { if ((window.innerHeight ...

Disabling dates in Kendo Date Time Picker (Angular): An easy guide

<input id="startDate" kendo-date-time-picker k-ng-model="vm.startDate" k-on-change="vm.updateStartDate()" required /> Can someone please explain how to incorporate disabled dates into this date picker without utilizi ...

When trying to convert Flow to TS, I encountered an error stating 'Unable to use component as a JSX component' after importing it from an installed library

I recently embarked on the task of upgrading an older React 15 codebase with Flow types to a more current Create React App (CRA) setup using TypeScript. To facilitate the conversion, I utilized the flow-to-ts script that converted all the necessary files. ...