Transform JSON object to a class/interface object using Typescript

I am currently working on converting an API response into a TypeScript class or interface.

The API is returning a list of objects with various properties, but I only require a few specific properties from the response object.

Example of API Response:

    [{
    'Id' : 1,
    'Name': 'test',
    'Description: 'Test',
    'PropertyX': 'x',
    'PropertyY' : 'y'
    },
    ...]

Typescript Class Example:


    Class Response {
     Id: string;
     Name: string;
    }

I would appreciate any suggestions on the best approach to convert the JSON object into a TypeScript object.

Answer №1

If you want to streamline the properties used in your app, it's best to create a specific interface for them and disregard the unnecessary ones:

For instance, if your response data includes various properties but you only need Id and Name, define an interface like this:

interface IMyObject {
  Id: String;
  Name: String;
}

You can then cast your response as IMyObject[] throughout your application.

For example, when defining a function that utilizes your response:

function myFunction(response: IMyObject[]) { ... }

Similarly, when you need to return that specific type, you can directly cast it:

return response as MyObject[];

Additionally, to exclude extraneous properties from your object, utilize .map:

const formattedResponse: IMyObject = reponse.map(item => {
  Id: item.Id,
  Name: item.Name
});

Answer №2

Utilize the forEach method to generate a new object with the desired properties.

myarray=[];
 ngOnInit() {
     this.myvalues();

  }


    myMethod()
        {
           const response = [{
            'Id' : 1,
            'Name': 'test',
            'Description': 'Test',
            'PropertyX': 'x',
            'PropertyY' : 'y'
          }, {
            'Id' : 2,
            'Name': 'test2',
            'Description': 'Test2',
            'PropertyX': 'x2',
            'PropertyY' : 'y2'
          }
        ];

        response.forEach(value=>{
         this.myarray.push(
               {
                'ID':value.Id,
               'Name':value.Name
              }
            )
        });
        console.log(this.myarray);

VIEW WORKING DEMO

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

A guide on retrieving an object property in keen.io

When using the extractions API in keen.io, I'm facing an issue where specific properties that are objects are not being retrieved. curl "https://api.keen.io/3.0/projects/PROJECT_ID/queries/extraction?api_key=READ_KEY&event_collection=COLLECTION_N ...

JSON file not found by the system

I am currently working on a basic program that consists of 3 files: 1. An HTML file named index.html 2. A JavaScript file named app.js 3. A JSON dataset called dataset.json I am struggling to make the browser recognize the data in my program. This is ...

What are some strategies to prevent the occurrence of "<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">"?

I recently created a basic web service using the VB.NET "WCF Rest Service Application" project template (Was this a good decision?). It is functioning well, except for the unexpected addition of: <string xmlns="http://schemas.microsoft.com/2003/10/Seri ...

Creating a personalized JSON object using the outcome of a GROUP BY statement in PHP

I am currently attempting to retrieve a JSON object from a PHP script. Here is the code I have written so far: <?php $connection=pg_connect("host=localhost port=5432 dbname=postgres user=postgres password=root") or die("Can't connect to database ...

How to detect changes in Angular 2 using a separate service

Within my AuthService, I store real-time user data and a method for logging in. When the 'Login' button is clicked, the AuthService is called to retrieve updated user data from the server and update the value of 'this.user'. As a resul ...

Transmitting intricate data sets to the WEB API

I am experiencing difficulties in sending a JSON complex object to my User control within my web API project. Every time I try, I encounter a 404 error. While controls with routes like /api/{control}/{action}/{id} are functioning properly, those with the r ...

Click on the photo and drag your mouse outside of it to zoom out [Angular2]

HTML <div class="zoomPhoto" *ngIf="zoomed" (click)="unZoomPhoto()"> <img src="{{currentPhoto}}" [style.margin-left.px]="-(zoomedPhotoWidth/2)" [style.margin-top.px]="-(zoomedPhotoHeight/2)" #photo /> </div> CSS .zoomPhoto{ backg ...

How to link data from a service to an Angular component in a way that ensures the component gets updated whenever there is new data in the service

When data is updated in a service, how can I ensure that the changes are reflected in a component? In my application's header, there is a button that allows users to switch between English and Spanish. However, while the text in the header (a compone ...

Problems arising from positioning elements with CSS and organizing list items

I've been working on creating a navigation sidebar using Angular and Bootstrap, but I'm having trouble getting my navigation items to display correctly. APP Component HTML <div class="container-fluid"> <div class="row" id="header"&g ...

What is the best way to iterate through this JSON data and add it to a div in an HTML document?

Here is the structure of my JSON: { "content": [ { "title": "'I need some rest'", "description": "Descript One", "link": "http://www.google.com/?id=90#hhjjhjC-RSS", "guid": "http://www.google ...

The GraphQl Code Generator fails to correctly generate the graphql() function in Next.js applications

While working on my next.js project, I integrated GraphQL to generate types for queries. However, the code generator is not functioning properly and displaying an error message: "The query argument is unknown! Please regenerate the types." within the gql.t ...

Exploring Postgres Commands for Manipulating JSON Arrays

One of my tables is called cust_data and it stores ids along with JSON objects. I need to create postgres select queries to retrieve: Get all ids where the persons array does not contain "gender": "Female" [this should return id#3 from the data below] Re ...

The type 'string' cannot be assigned to type 'ImageSourcePropType'

Context Attempting to utilize a SVG component in React Native with the xlinkHref property within an Image tag. The SVG file was converted into a React Native Component (TSX) using the tool provided at . While simple SVG icons have been successfully used be ...

What is the best way to create a case-insensitive sorting key in ag-grid?

While working with grids, I've noticed that the sorting is case-sensitive. Is there a way to change this behavior? Here's a snippet of my code: columnDefs = [ { headerName: 'Id', field: 'id', sort: 'asc', sortabl ...

Unable to establish a connection to 'X' as it is not recognized as a valid property

Trying to implement a Tinder-like swiping feature in my Angular project, but encountering an error stating that the property parentSubject is not recognized within my card component. Despite using the @Input() annotation for the property, it still fails to ...

Text hidden within Android fragment

Note: The JSON data is not parsed in the CardView. Main Fragment I implemented a fragment to display data on every item click using a slider menu. I wrote code to parse JSON data using Retrofit web service. public class Physical_Geography_Activity exten ...

Turn off the interconnected route while utilizing npm to display the tree of dependencies

If I want to display the project's dependencies tree using npm, I would use the following command: npm ls lodash The output will look something like this: > npm ls lodash npm info using [email protected] npm info using [email protected] ...

Decide on the chosen option within the select tag

Is there a way to pre-select an option in a combobox and have the ability to change the selection using TypeScript? I only have two options: "yes" or "no", and I would like to determine which one is selected by default. EDIT : This combobox is for allow ...

Sending properties to MUI Box component enhancer (Typescript)

I'm having trouble figuring out how to pass props to override the Box component. I specifically need to pass position="end" as InputAdornment requires it, but I can't seem to find the proper way in the documentation. Here's the complete co ...

Changing LinkedHashMap<String,String> into an object in Java

Let's dive straight into my inquiry and delve deeper into the context later. Specific Question: I have a LinkedHashMap<String, String> representing a specific object. What is the most efficient way to convert it into that object? I am aware th ...