Converting JSON data into an Angular object

I'm struggling to map the JSON data below to an Angular 7 object:

    [
      {
        "id": "123456",
        "general": {
          "number": "123",
          "name": "my name 1",
          "description": "My description with <li> html tags </li>"
        },
        "option1": {
          "name": "option1 name"
        },
        "option2": {
          "suboption2": {
            "name": "suboption2 name"
          }
        }
      },
      {
        "id": "789123",
        "general": {
          "number": "456",
          "name": "my name 2",
          "description": "My description with <li> html tags </li>"
        },
        "option1": {
          "name": "option2 name"
        },
        "option2": {
          "suboption2": {
            "description": "My description with <li> html tags </li>"
          }
        }
      }
    ]

I attempted to create a MyClass instance using fields that match those in the JSON file and then cast the JSON data to this class, but I encountered challenges along the way.

Answer №1

To streamline the data transformation process, I suggest implementing a mapper service. This service will take your DTOs (data transfer objects which represent your JSON response) as input and generate instances of your MyClass object as output.

Within the map function of your service, you can iterate through the array of DTOs and instantiate a new MyClass object for each DTO. Finally, the function will return an array containing all the MyClass instances created.

map(myClassDtos:MyClassDTO[]):MyClass[]{
    return myClassDtos.map(dto=>{
        return new MyClass(...);
    });
}

Answer №2

To start off, I suggest restructuring your JSON format to make it more organized and easier to work with:

[
    {
        "id": "123456",
        "general": {
            "number": "123",
            "name": "my name 1",
            "description": "My description with <li> html tags </li>"
        },
        "options": [
            {
                "name": "option1 name"
            },
            {
                "name": "option2 name",
                "suboptions": [
                    {
                        "name": "suboption1 name"
                    }
                ]
            }
        ]
    },
    {
        "id": "789123",
        "general": {
            "number": "456",
            "name": "my name 2",
            "description": "My description with <li> html tags </li>"
        },
        "options": [
            {
                "name": "option1 name"
            },
            {
                "name": "option2 name",
                "suboptions": [
                    {
                        "name": "suboption1 name"
                    },
                    {
                        "name": "suboption2 name"
                    }
                ]
            },
            {
                "name": "option3 name",
                "suboptions": [
                    {
                        "name": "suboption1 name"
                    },
                    {
                        "name": "suboption2 name"
                    }
                ]
            }
        ]
    }
]

Next, create model interfaces to represent each item in the JSON array:

main-element.ts

import { General } from './general';
import { Options } from './options';

export interface Element {
    id?: number;
    general?: General;
    options?: Options[];
}

generl.ts

export interface General {
    number?: number;
    name?: string;
    description?: number;
}


import { Suboptions } from './suboptions';

options.ts

export interface Options {
    name?: string;
    suboptions?: Suboptions[];
}

suboptions.ts

export interface Suboptions {
    name?: string;
}

Lastly, when mapping the data, utilize the following approach:

import { Component } from '@angular/core';
import { Element } from './models/main-element';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private elementsList: Element[] = [];

  constructor(){
  }

  mapJSON(){
      this.elementsList = this.someJsonString; //Insert your JSON data here
      console.log(this.elementsList);
  }
}

If you print out the elementsList object in the console, you will see the structured data as shown in the screenshot below:

https://i.sstatic.net/iduMg.png

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

Build for Node.js using TypeScript with full functionality

When compiling TypeScript for Node.js using tsc --module commonjs --target ES5 I face limitations with async/await and generators as tsc doesn't know how to handle them in ES5. To address this issue, I can compile TypeScript for Node.js with tsc - ...

Why aren't the child route components in Angular 6 loading properly?

I have encountered a small problem. I developed an app using Angular 6 with children routes implemented like this: { path:'pages', component:DatePagesComponent, children : [ {path:'404', component:Error404C ...

Ending the connection in SignalR upon $destroy

I am currently working on a page that is utilizing SignalR, Angular, and Typescript. Upon the destruction of the current $scope (such as during a page change), I make an attempt to disconnect the client from the SignalR server: Controller.ts $scope.$on(&q ...

Enhance your React Native experience with IntelliSense recommending react-native/types over react-native

I am trying to bring in <View from react-native, but instead, I am getting react-native/types How can I resolve this issue? This is a new project starting from scratch and I followed the documentation by adding TypeScript as instructed: yarn add --dev ...

Implementing onClick functionality to change background color with styled components

Is there a way to apply background color when a user clicks on any page in pagination using React styled components? I was able to achieve this with simple CSS by adding the class ".selected" which had a background-color of red, but now I need to use React ...

Error encountered when running Angular 11 with SSR using @nguniversal/express-engine: "ReferenceError: globalThis is not defined"

Encountering issues while attempting to integrate @angular/fire with Angular 11 and @nguniversal/express-engine for server-side rendering (SSR). Upon initializing AngularFireModule in app.module.ts, errors arise when running the commands npm run dev:ssr or ...

In React TypeScript, the property types of 'type' are not compatible with each other

I have a unique custom button code block here: export enum ButtonTypes { 'button', 'submit', 'reset', undefined, } type CustomButtonProps = { type: ButtonTypes; }; const CustomButton: React.FC<CustomButtonProp ...

Angular 8 update triggers issue with Material-UI dropdown menu on IE11

Encountering an error in an Angular 8 application with Material 8 on IE11 when the material menu is opened: Unable to get property 'opacity' of undefined or null reference This issue did not occur with Angular 7.2. IE11 Version: 11.1146.16299.0 ...

Troubleshooting Problems with Google Maps and Javascript/JSON in Internet Explorer

Currently, I am utilizing the Google Maps API to construct a map that displays store locations in close proximity to a user-specified location. Everything is functioning properly, however, I am encountering an error in Internet Explorer that I would like t ...

What could be the reason my RxJS Observable chain does not run again when new emissions are made?

Currently, I am facing a unique challenge while working with RxJS in an Angular service. The issue revolves around two observable chains designed to enhance a stream of notifications with user data. One chain functions correctly, allowing for multiple trig ...

What is the best way to generate a switch statement based on an enum type that will automatically include a case for each enum member?

While Visual Studio Professional has this feature, I am unsure how to achieve it in VS Code. Take for instance the following Colors enum: enum Colors { Red, Blue, When writing a switch statement like this: function getColor(colors: Colors) { swi ...

What is the best way to add JSON data received from an AJAX response to multiple classes?

Currently, I am honing my skills in jquery and have hit a bump in the road. I am receiving JSON data from a fantasy football API and am trying to map over the data to assign each team owner and name to their own div. My main query revolves around how I can ...

How to highlight a specific date in angular 10's mat-date-range-input using a specific

Currently, I am working on a project that involves integrating the MatDatePicker component from Angular Material to create a customized calendar for specific dates. However, I have run into an issue when trying to add custom CSS classes to certain calendar ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

Navigating with query parameters in Angular 5

Currently, I am developing my angular 5+ application and utilizing the AuthGuardService. My scenario involves redirecting from another php application that sends form data through a query string. http://localhost:44200/#/users/save?first_name=John&las ...

Displaying HTML content using Typescript

As a newcomer to typescript, I have a question regarding displaying HTML using typescript. Below is the HTML code snippet: <div itemprop="copy-paste-block"> <ul> <li><span style="font-size:11pt;"><span style="font-family ...

From a series of arrays filled with objects, transform into a single array of objects

Upon using my zip operator, I am receiving the following output: [ [Obj1, Obj2, ...], [Obj1, Obj2, ...] ]. To achieve my desired result, I am currently utilizing the code snippet below: map(x => [...x[0], ...x[1]]) I am curious to know if there exists ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

What is the best way to extract data from an [object Object] and store it in an Array or access its values in Angular?

My Angular code is written in the component.ts file. I am fetching data from a backend API and using console.log to display the data. getInfo() { const params = []; params.push({code: 'Code', name: 'ty_PSD'}); params ...

A guide to incorporating Material-UI ThemeProvider and WithStyles with Typescript

I've been feeling frustrated lately as I've been dedicating the past few days to migrating my React application from JavaScript to TSX. While I appreciate the type checking that TSX provides, I'm struggling with understanding how to implemen ...