Convert a nested JSON array into TypeScript class objects

Within the database exist two distinct entities: 'person' and 'name'. These entities share a many-to-many relationship with the properties 'from' and 'to'.


 Person              PersonName                   Name
----------          -------------               -----------
id: number          from: number                 id: number
                    to: number                   firstname: string
                                                 lastname: string

The Spring-Boot backend is responsible for sending a json-array containing all persons to the Angular frontend.

An example of a Json Object representing a Person would look like this:

{
 id: 1, 
 names: [
    {
    from: 1733,
    to: 1735,
    name:  {
            id: 1,
            firstname: John,
            lastname: Doe
           }
    }, ...
]

The structure of my Angular service is as follows:

export class PersonService {

    constructor(private http: HttpClient) { }

    getAll(): Observable<any> {
        return this.http.get('//localhost:8080/person')
    };
}

I've created classes for each entity and their relationships. For instance, the 'name' class takes on the following form:

export class Name {
    id: number;
    firstname: string;
    lastname: string;
}

How can I convert the Json-Array into instances of the respective Typescript classes? The objective here is ensuring that the getAll() function returns an Observable of type Person[].

Despite making the change from

this.http.get('//localhost:8080/person')
to
this.http.get<Person[]>('//localhost:8080/person')
, it fails to yield a valid Person array.

Answer №1

If you find yourself in need of a mapper function for your subscribe, consider using the one provided below as an example. Feel free to modify the mapper according to your specific requirements.

For instance:

this.userService.getAll().subscribe(data => this.users = this.mapper(data))

const data = {
 id: 1, 
 names: [
    {
    from: 1733,
    to: 1735,
    name:  {
            id: 1,
            firstname: "John",
            lastname: "Doe"
           }
    },
    {
    from: 1735,
    to: 1736,
    name:  {
            id: 2,
            firstname: "Joan",
            lastname: "Smith"
           }
    }
]
}

const mapper = (toMap) => 
  toMap.names.map(item=> item.name)
  
console.log(mapper(data))

Answer №2

When using this.getAll() function, you can subscribe to the response and cast it to a Name array by parsing it as JSON.

This allows you to easily work with the data in a structured format.

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-universal | firestore-admin | code: 'app/invalid-authentication' | connection timeout

import * as admin from 'firebase-admin'; var serviceAccount = require('./keys/keyfile.json'); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: "https://test.firebaseio.com" }); var registrationT ...

Tips for ensuring the correct typing of a "handler" search for a "dispatcher" style function

Imagine having a structure like this: type TInfoGeneric<TType extends string, TValue> = { valueType: TType, value: TValue, // Correspond to valueType } To prevent redundancy, a type map is created to list the potential valueType and associate i ...

Determine the specified keys within a JSON object using Python

My goal is to generate JSON output that includes a list of MAC addresses and corresponding timestamps for each address. Here's an example of the desired output: [ "B2:C7:23:10:A0": [ "2014-04-04T21:30:46.348900800Z", "2014-04-04T21:30:46.348 ...

JSON retrieval line

Hi there, this is my first time posting here so I hope my question is clear :-) I have a PHP page that retrieves JSON data from a remote website. This JSON includes a list of names, and for each name, I need to fetch additional details from another JSON p ...

Using GSON to convert a 2D JSON array into a bean object

I'm having trouble mapping this nested array of rows and elements to my javabean using Gson. Is it possible for Gson to handle this kind of mapping? I've also attempted a different approach, which is commented out in the Java code below. package ...

Tips for efficiently storing a large JSON object in a session storage?

Currently, I am working on a project that involves saving rows retrieved from a database as JSON data to the user's session. This application utilizes jQuery on the client-side and is powered by the Spring MVC framework along with Hibernate on the bac ...

Troubleshooting a Custom Pipe Problem in Angular Material Drag and Drop

Currently, I am working on a project involving Angular Material Drag And Drop functionality. I have created a simplified example on StackBlitz which you can access through this link: here The project involves two lists - one containing pets and the other ...

The 'catch' property is not found within the type 'PromiseLike<void>'

Help! I'm encountering a Typescript Error. An issue is arising with the 'catch' property on type 'PromiseLike<void>'. I am using Ionic and facing an error in the line containing catch: sendrequest(req: connreq) { var p ...

Filtering in JavaScript can be efficiently done by checking for multiple values and only including them if they are not

In my current coding challenge, I am attempting to create a filter that considers multiple values and only acts on them if they are not empty. Take the following example: jobsTracked = [ { "company": "Company1", ...

HTTP Interceptor never finishes executing (finalization is never triggered)

In my angular 8 project, I created a basic HttpInterceptor that simply duplicates the original request and includes an additional parameter: @Injectable() export class RequestHeadersInterceptor implements HttpInterceptor { intercept(request: HttpReques ...

Unique identifiers and peculiar symbols for the process of serializing data using flat buffers

I have a Json dataset similar to this: { "!type": "alarm", "$": { "12279": { "!type": "alarm", "title": "Default", "$": { "5955": { "!type": "alarm", "name": "Wake", "day": "SUN", " ...

"Exploring the power of D3, TypeScript, and Angular 2

I am facing challenges incorporating D3 v4 with Angular 2 (Typescript). While exploring D3 v4, I have referred to several solutions on StackOverflow without success. I have imported most of the necessary D3 libraries and typings (utilizing TS 2.0) and adde ...

Ways to prevent the use of the JavaScript increment (++) or decrement (--)

I have created two functions for a multi-step configuration on a webpage. protected clickNext(event:any, config:any) : any{ this.activeIndex++; } protected clickPrev(event:any, config:any) : any{ this.activeIndex--; } Here are the buttons: < ...

What is the best way to retrieve the object of the selected option from a single select input in Angular

I'm currently working with an array of objects that looks like this: let myArray = [{'id':1,'Name':"ABC"},{'id':2,'Name':"XYZ"}] I'm trying to retrieve object values based on a dropdown selection, but so ...

Webpack and TypeScript are throwing an error stating that `$styles` is not defined

I've encountered an issue with my typescript SharePoint spfx solution. After compiling using webpack, my $styles variable becomes undefined even though I am able to use the class names directly. It seems like there might be a configuration problem at ...

Generating an instance of an enum using a string in Typescript

Having trouble accessing the enum members of a numeric enum in TypeScript using window[name]. The result is an undefined object. export enum MyEnum { MemberOne = 0, MemberTwo = 1 } export class ObjectUtils { public static GetEnumMembers(name ...

One way to add a JSON object to an empty JSON array using Javascript involves pushing

Currently, I am facing an issue with an empty JSON array. shoppingCart: [] In addition to the empty array, I also have a JSON object defined as follows: let product = {"name": "name", "price": "price", "quantity": "quantity", "logoPath": "logoPath"}; M ...

Authentication on a Basic HTML level is an integral part of Spring Security

Embarking on the creation of a RESTful webservice for a new project has been quite the learning experience. I am currently working on adding basic authentication to the webserver, requiring credentials from every application that will utilize the service. ...

Is there a way to program a function that can automatically trigger or refresh an HTTP POST method?

How can I create a method in a distant component that will run a POST request when a button is clicked? I believe I need to use a service in this situation. It's not necessary for it(this.qwe) to be in the constructor, it's just an example... ...

Params are not being sent by Angular HttpRequest

I have been attempting to pass parameters in a basic GET request using HttpRequest, but it seems that the parameters are not being sent. let params = new HttpParams(); params.set("page", "4"); let req = new HttpRequest<any>( &q ...