Transform a collection of objects into instances of a class

I have a scenario where I am fetching an array of objects from PHP and my goal is to transform this data into instances of a class called ContentData.

The current solution that I have seems to work fine, but deep down I sense that there might be a more elegant way to achieve the same outcome.

return this.http.post("get-content.php", urlParams)
.map(this.extractData)
.map(array => {
    let newArray = Array<ContentData>();
    array.forEach(obj => {
        newArray.push(new ContentData().deserialize(obj));
    });
    return newArray;
})
.catch(this.handleError)

private extractData(res: Response): any {
    return res.json();
}

Is there a more efficient method rather than looping through the array data in this manner?


The response received from PHP looks like this:

[
{"id":"1","dock_id":"46","type":"TEXT","content":"{\"text\": \"<p>test<\/p>\"}","last_updated":"2017-08-09 03:10:28","json":null},
{"id":"2","dock_id":"46","type":"TEXT","content":"{\"text\": \"<p>test test<\/p>\"}","last_updated":"2017-08-09 03:10:28","json":null}
]

The desired output should be [ContentData, ContentData, ...] (a flat 1D array).

(2) [ContentData, ContentData]
0 : ContentData {content: "{"text": "<p>test</p>"}", dock_id: "46", type: 0, last_updated: "2017-08-09 03:10:28"}
1 : ContentData {content: "{"text": "<p>test test</p>"}", dock_id: "46", type: 0, last_updated: "2017-08-09 03:10:28"}
length : 2

Answer №1

If I interpret your code correctly, there are multiple ways to enhance it:

  • Employing async functions for a more linear code structure
  • Utilizing .map() instead of using loops and pushing elements

An example implementation could look like this:

public async fetchAndProcess(/* arguments */) {
  try {
    const response = await this.http.post("get-content.php", urlParams); // Assuming fetch
    const jsonData = await response.json();
    return result = jsonData.map(item => new ContentData().deserialize(item));
  } catch (error) { this.handleError(error); }
}

Additionally, I recommend either creating a static method like ContentData.fromSerialized() or adjusting the constructor of ContentData to accept item. However, this falls more into the realm of code styling.

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

Leveraging components from external modules within sub-modules

So, I've created a module to export a component for use in different modules. However, I'm facing an issue with how to properly utilize this component within child modules of another parent module. While I have imported the first module into the ...

Is there a way to retrieve the anticipated DOM structure prior to the initialization of the view?

Consider this component: @Component({ selector: "form-control", template: ` <div class="form-group" #div> <label [for]="inputId">{{label}}</label> <ng-content></ng-content> <small [id]="helpId" cl ...

Retrieve upcoming route details within canDeactivate guard in the updated Angular2 router

Is there a way to retrieve the upcoming route information within the "canDeactivate" guard of Angular 2's new router? ...

Typescript sometimes struggles to definitively determine whether a property is null or not

interface A { id?: string } interface B { id: string } function test(a: A, b: A) { if (!a.id && !b.id) { return } let c: B = { id: a.id || b.id } } Check out the code on playground An error arises stating that 'objectI ...

Implementing an overlay feature upon clicking a menu item - here's how!

I am currently working on implementing an overlay that displays when clicking on a menu item, such as item 1, item 2 or item 3. I have managed to create a button (Click me) that shows an overlay when clicked. Now, I would like to achieve the same effect wh ...

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

What is the best way to reference typescript files without using absolute paths?

As typescript does not seem to have built-in support for absolute path references (according to this GitHub issue), it becomes difficult to organize and maintain my file references. With TypeScript files scattered across various locations in my folder stru ...

The import component path in Angular 4/TypeScript is not being recognized, even though it appears to be valid and functional

I'm currently working on building a router component using Angular and TypeScript. Check out my project structure below: https://i.stack.imgur.com/h2Y9k.png Let's delve into the landingPageComponent. From the image, you can see that the path ...

Angular Dialog Component: Passing and Populating an Array with Mat-Dialog

Here's the situation: I will enter a value in the QTY text field. A Mat dialog will appear, showing how many quantities I have entered. My question is, how can I iterate an object or data in the afterclosed function and populate it to the setItem? Cur ...

The absence of color gradations in the TypeScript definition of MUI5 createTheme is worth noting

Seeking to personalize my theme colors in MUI5 using TypeScript, I am utilizing the createTheme function. This function requires a palette entry in its argument object, which TypeScript specifies should be of type PaletteOptions: https://i.stack.imgur.com ...

The functionality of PrimeNg TabView does not support observables

I am facing an issue with the PrimeNG TabView tabs when trying to populate them with data fetched from the server using Observables. I have included a sample example here for reference: https://stackblitz.com/edit/primeng-nx7ryc?file=app%2Fapp.component.t ...

A guide on using tsc to build a local package

Unique Project Structure I have a unique monorepo structure (utilizing npm workspaces) that includes a directory called api. This api directory houses an express API written in typescript. Additionally, the api folder relies on a local package called @mya ...

Leveraging Apostrophe CMS for building a decoupled single page application

I am currently developing a single page application inspired by the design of My goal is to separate the content management system from the presentation layer (most likely using Vue or Angular) and fetch data from a JSON API. The client initially prefers ...

Separate configurations for Webpack (Client and Server) to run an Express app without serving HTML files

I am currently developing an application with a Node Backend and I am trying to bundle it with Webpack. Initially, I had a single Webpack configuration with target: node. However, I encountered issues compiling Websockets into the frontend bundle unless I ...

Customize button appearance within mat-menu in Angular versions 2 and above

Is there a way to style my mat-menu to function similar to a modal dialog? I am having difficulty with the styling aspect and need advice on how to move the save and reset buttons to the right while creating space between them. I have attempted to apply st ...

Is it possible to consistently show the placeholder in mat-select regardless of the item currently selected?

I am looking to keep the mat-select element displaying the placeholder at all times, even if an option has been selected. Below is my HTML code: <mat-select [formControlName]="'language'" placeholder="Language"> <mat-option value=" ...

ES6 import of CSS file results in string output instead of object

Too long; Didn't read I'm facing an issue where the css file I import into a typescript module resolves to a string instead of an object. Can someone help me understand why this is happening? For Instance // preview.ts import test from './ ...

substitute one item with a different item

I am facing an issue with updating the address object within an organization object. I receive values from a form that I want to use to update the address object. However, when I try to change the address object in the organization using Object.assign, i ...

Encountering a Nextjs hydration issue after switching languages

I am facing an issue with my Next.js project using version v12.2.4 and implementing internationalization with i18next. The project supports two languages: Italian and English. Strangely, when I switch to English language, the app throws errors, while every ...

The issue of resolving NestJs ParseEnumPipe

I'm currently using the NestJs framework (which I absolutely adore) and I need to validate incoming data against an Enum in Typscript. Here's what I have: enum ProductAction { PURCHASE = 'PURCHASE', } @Patch('products/:uuid&apos ...