Tips for synchronizing response JSON with TypeScript interface in Angular 6

I am retrieving a list of files that have been uploaded from a backend endpoint, and it comes back in this format:

[
    {
        "filename": "setup.cfg",
        "id": 1,
        "path": C:\\back-end\\uploads\\setup.cfg",
        "uploaded_at": "Fri, 01 Jun 2018 09:25:19 -0000"
    },
    {
        "filename": "57760713_1467275948.jpg",
        "id": 2,
        "path": "C:\\back-end\\uploads\\57760713_1467275948.jpg",
        "uploaded_at": "Mon, 04 Jun 2018 09:09:59 -0000"
    },

    .
    .
    .

]

Along with this data, I have a TypeScript interface designed like so:

export interface UploadModel {
    id: number;
    name: string;
    path: string;
    uploadedAt: Date;
}

The issue lies in the naming conventions used; the returned data follows snake_case as uploaded_at while my interface uses camelCase as uploadedAt.

I'm looking to fetch this information from the backend using the following code snippet:

  getUploads(): Observable<UploadModel[]> {
    this.http.get(UPLOADS_ENDPOINT)
     .map((response: Response) => {

         // Need to parse the JSON response here and return an array of UploadModels

     });
  }

Any tips on how to effectively map these two representations without manually iterating through the array of JSON objects?

Answer №1

A custom function can be created to convert keys from underscored format to camel case. Although the provided implementation is basic, it can be enhanced for better efficiency and potentially recursive handling of nested objects.

const data = [
  {
    "filename": "setup.cfg",
    "id": 1,
    "path": "C:\\back-end\\uploads\\setup.cfg",
    "uploaded_at": "Fri, 01 Jun 2018 09:25:19 -0000"
  },
  {
    "filename": "57760713_1467275948.jpg",
    "id": 2,
    "path": "C:\\back-end\\uploads\\57760713_1467275948.jpg",
    "uploaded_at": "Mon, 04 Jun 2018 09:09:59 -0000"
  }
];

function underscoreToCamel(key: string) {
  return key.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });
}

function convertKeys(input: any[]) {
  const output = [];
  for (const item of input) {
    const obj = {};
    for (const key in item) {
      obj[underscoreToCamel(key)] = item[key];
    }
    output.push(obj);
  }
  return output;
}

const result = convertKeys(data);
console.log(result);

Output:

[
    {
        "filename":"setup.cfg",
        "id":1,
        "path":"C:\\back-end\\uploads\\setup.cfg",
        "uploadedAt":"Fri, 01 Jun 2018 09:25:19 -0000"
    },
    {
        "filename":"57760713_1467275948.jpg",
        "id":2,
        "path":"C:\\back-end\\uploads\\57760713_1467275948.jpg",
        "uploadedAt":"Mon, 04 Jun 2018 09:09:59 -0000"
    }
 ]

Answer №2

Unfortunately, there is no simple solution available.

It may be challenging to deal with your response right now, but avoiding it will only make things more difficult in the long run.

Here are three possible approaches you can consider:

  1. You could create two distinct interfaces - IUploadResponse and IUpload. Objects that implement these interfaces will need to have explicit mappings set up in their constructors.

  2. An alternative option is to design an abstract class with a transformation method that handles the mapping process.

  3. Another approach would be to develop a converter that transforms snake_case variables into camelCase format. While this method offers reusability, keep in mind that it may limit certain naming conventions like renaming filename to name. Additionally, this approach does not directly create objects, so you may not access features like typeof or instanceof.

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

The element 'nz-list-item-meta-title' in NG-ZORRO is unrecognized

After installing NG-ZORRO for my project, I decided to start by incorporating their list component. However, I encountered errors with elements such as: 'nz-list-item-meta-title' and 'nz-list-item-action' not being recognized. I have e ...

What is the best way to determine if a user is connected to the internet using Angular2?

Is there a way to check for internet connectivity in Angular 2 when hitting an API? Sometimes, the user may be offline when accessing the server through the app. Are there specific status codes or methods to determine internet connectivity? Note: I came a ...

There seems to be a problem retrieving the JSON file

My JavaScript file is designed to fetch a JSON file and execute a function if successful. If there's an error, it should display an alert window with the message "error". However, despite checking the syntax, I keep receiving an error alert every time ...

Retrieve a file through a POST request with node.js

Hi everyone, I'm trying to create a "export to excel" functionality in Node.js for a page. By using Chrome DevTools, I discovered that the file is downloaded after a post request, so I need to replicate it. var request = require('request' ...

How to designate the specific container to be updated in the XMLHTTP JSON code within a Joomla website?

Below are some functions that were created by a former developer who is no longer with the company. These functions query a database and return JSON code to update the inner HTML of a specific div. I have now been tasked with setting up a typeahead search ...

What is the process for creating a jQuery object in TypeScript for the `window` and `document` objects?

Is there a way to generate a jQuery object in TypeScript for the window and document? https://i.stack.imgur.com/fuItr.png ...

Encountering a problem in Django when attempting to serialize decimal points, error message reads: 'ValuesListQuerySet' does not contain the attribute '_meta'

I'm trying to serialize a FloatField model instance in django, specifically within a management command. Here's the code I have: def chart_data(request): i = 1 chart = open_flash_chart() chart.title = t for manager in FusionMa ...

Struggling with converting JSON to JAXB with Jackson's ObjectMapper

I've encountered a challenge in my JAX-RS project related to JSON to JAXB deserialization using Jackson's ObjectMapper. The technologies/frameworks being used include: Jackson (FasterXML) 2.8.5 JAXB 2.2 The issue arises specifically with all I ...

Sending Angular signal from child component to parent component

While working in Angular, I have been utilizing event emitters to transmit data from a child component to a parent component. This allows the parent component to update shared data based on notifications from the child. Now with Signal being introduced i ...

Identifier for md-radio-group

In my Angular 4 Material application, I have a set of radio buttons grouped together: <md-radio-group fxLayout fxLayoutAlign="center center" fxLayoutGap="30px"> <md-radio-button value="1">Date</md-radio-button> <md-radio-butto ...

Leveraging Font Awesome and Material Icons within ngFor in Angular 2

I have a unique situation where I need to display a dynamic list of icons in a right side bar. These icons are added to the sidebar based on user actions and are displayed using the ngFor directive. The challenge here is that some icons come from Font Awe ...

The plugin needed for the 'autoprefixer' task could not be located

Starting out in the world of Angular 2 development can be overwhelming, especially when trying to integrate with the Play framework on the back-end side. I recently came across a helpful post by Denis Sinyakov that walks through setting up this integratio ...

"Troubleshooting: Why are my Webpack 2 stylesheets

Recently, I made an update to my application (currently running on [email protected]) by switching from Webpack 1.x to Webpack 2.6.1. Despite following the migration documentation, upon running the application, the external stylesheets fail to load. M ...

Tips on effectively utilizing RABL partial templates while maintaining consistency

Currently working with Ruby on Rails 4 and incorporating the RABL gem into my project. I am seeking a way to reuse templates by rendering the show.json.rabl view from the index.json.rabl while following the standards outlined at jsonapi.org (source: RABL d ...

Retrieve additional information from JSON.stringify using a Web API Post request

Having an html page with a button, certain functions hold importance: function updateClick() { SOP10100 = new Object(); SOP10100.CUSTNMBR = "5000"; SOP10100.SHIPMTHD = "FedEX"; SOP10100.SOP10200 = [{ itemnmbr: "120604", quantity: 3, unitpr ...

Exploring the power of utilizing multiple classes with conditions in Angular 2+

Can you help me figure out how to use a condition for selecting multiple classes with [ngClass] in Angular? <td> <span [ngClass]="{ 'badge badge-success': server.type === 'PRODUCTION', 'ba ...

What is the best way to search for an Enum based on its value?

One of my challenges involves an enum containing various API messages that I have already translated for display in the front-end: export enum API_MESSAGES { FAILED_TO_LOAD = 'Failed to load data', TOKEN_INVALID = 'Token seems to be inva ...

Transferring API information into a nested array and displaying the outcome

Currently, I am utilizing an API to fetch an array of users from which I sort them and collect those with a personalTrainerId matching my userId into an array. The ultimate goal is to render these users as cards on the interface. The desired format for th ...

Python: Exploring JSON Data

Is there a way to extract data specific to a district (such as Nicobars, North and Middle Andaman...) from ? I am trying to extract the Active cases by simply searching for the district name without having to specify the state every time. Currently, I&apos ...

Is it possible to create Interactive Tabs using a Global BehaviorSubject?

Trying to adjust tab visibility based on different sections of the Ionic app, an approach involving a global boolean BehaviorSubject is being utilized. The encapsulated code has been condensed for brevity. In the provider/service globals.ts file, the foll ...