Creating customized object mappings in Typescript

In my current Angular project, I am working on mapping the response from the following code snippet:

return this.http.get(this.url)
      .toPromise()
      .then(response => response as IValueSetDictionary[])
      .catch(this.handleError);

The response is being mapped to the interface shown below:

export interface IValueSetDictionary {
  valueSet: {};
}

This process involves handling a JSON response received from a third-party service that looks like this:

{
  "<CONCENTRATE> | 6": "<CONCENTRATE>",
  "<PHYSICAL> | 5": "<PHYSICAL>",
  "NYMEX WARRANT IN MT | 12": "NYMEX WARRANT IN MT",
  "SHFE WARRANT | 13": "SHFE WARRANT"
}

I need some assistance with removing the '<' and '>' symbols from the response.

The desired output should look like this:

{
  "CONCENTRATE | 6": "CONCENTRATE",
  "PHYSICAL | 5": "PHYSICAL",
  "NYMEX WARRANT IN MT | 12": "NYMEX WARRANT IN MT",
  "SHFE WARRANT | 13": "SHFE WARRANT"
}

Essentially, I aim to eliminate the '<>' tags during the mapping process in TypeScript, but I haven't found an elegant solution yet.

Answer №1

I am looking for a solution to remove the '<>' tags while mapping the response data. I haven't found a clean way to achieve this in typescript yet.

It's not just a typescript issue, the same applies to javascript as well. The key is to transform the objects you receive into the desired format. You can try something like the following code snippet:

return this.http.get(this.url)
      .toPromise()
      .then(response => response as IValueSetDictionary[])
      .then((value) => value.map((vs) => this.cleanValueSet(vs)))
      .catch(this.handleError);

The cleanValueSet function is responsible for replacing the unwanted characters and reconstructing the object:

private cleanValueSet = (vs: IValueSetDictionary): IValueSetDictionary => {
  const result = Object.keys(vs.valueSet).reduce((acc, rawKey) => {
    const key = rawKey.replace(/[\<\>]/g, '');
    const value = (vs.valueSet[rawKey] as string).replace(/[\<\>]/g, '');
    acc[key] = value;
    return acc;
  }, {} as { [key: string]: string });

  return { valueSet: result };
};

Answer №2

To tackle this issue, one possible strategy is to convert the object into a string, utilize Regular Expression to eliminate the brackets, and then reparse the modified version.

It's important to note: This method may pose challenges if the object includes keys or values that contain various bracket characters.

'A scenario where < special characters within brackets > are present'

function removeAngleBrackets(obj) {
    const jsonString = JSON.stringify(obj);
    const result= jsonString.replace(/<(.*?)>/g,'$1');
    return JSON.parse(result);
}

let o = {
  "<CONCENTRATE> | 6": "<CONCENTRATE>",
  "<PHYSICAL> | 5": "<PHYSICAL>",
  "NYMEX WARRANT IN MT | 12": "NYMEX WARRANT IN MT",
  "SHFE WARRANT | 13": "SHFE WARRANT"
}

console.log(removeAngleBrackets(o));

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

Issue: ALERT found in ./src/styles.scss (./node_modules/raw-loader!./node_modules/postcss-loader/lib?

Hello to all my fellow developers! I've been diving into the Angular 6 project recently and things are going smoothly for the most part. However, I keep encountering a warning in the console after running the application with (ng serve). WARNING i ...

What is the process for incorporating buttons into an Angular mat-table?

I have successfully utilized Angular mat-table to showcase data retrieved from a database: view the image description here <table mat-table [dataSource]="UserDataSourceFilters" class="mat-elevation-z1 mt-5"> <ng-co ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

When testing, the @Input() variable that is inherited and initialized in the child constructor will be null during ngOnInit

I am currently working on testing Angular components using jest. I encountered an issue where a component initializes a variable in its constructor that becomes null during ngOnInit when the component is tested, but remains as expected when the application ...

What is behind the inconsistency of RxJS versions?

Trying to set up a node/angular2 solution on cloud9 has been quite the challenge. Below is my package.json: { "name": "example", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www", "postinstall": "typings install", ...

Getting to grips with the intricacies of the Gradle "task" syntax

I'm having trouble grasping the syntax of Gradle tasks. After following a tutorial, I created a build.gradle file for building Angular4/SpringBoots projects with Gradle. The build.gradle file includes several task blocks: // added our development b ...

Creating a Docker image for an Angular application with Node.js

Currently, I am attempting to develop an Angular application within a Docker environment and then run it as a container locally using Node.js. I have utilized the following Dockerfile to build the image, however, I am unsure of what might be missing when ...

The art of creating an asynchronous function: A comprehensive guide

My goal is to download files from a Firebase bucket and then store them in a database. I need the download process to be asynchronous, ensuring that each file is fully downloaded and added to an array before moving on to the next one. However, my current ...

The stream-chat-js package is causing an Angular compile error due to the absence of an exported member named 'Client'

Encountering an issue while attempting to compile an Angular application using the Node version of Stream Chat package. ERROR in node_modules/getstream/types/getstream/index.d.ts(12,11): error TS2694: Namespace '"/Users/.../app/node_modules/stream-c ...

An issue arises with the Angular 7 application specifically on Mac clients when the production release is deployed

I am facing an issue with my Angular 7 application developed in Visual Studio. The application utilizes Entity Framework for data access. Strangely, everything works perfectly when I connect a Windows laptop or a MacBook Air (using Chrome or Safari) to the ...

Tips for transforming TypeScript Enum properties into their corresponding values and vice versa

Situation Imagine having an enum with string values like this: enum Fruit { Apple = "apple", Orange = "orange", Banana = "banana", Pear = "pear" } Users always input a specific string value ("apple", "banana", "orange", "pear") from a drop-down li ...

Combining conditions with concatenation in [ngClass]: A step-by-step guide

My dilemma involves a div that I want to blur or reduce opacity on mouse enter. To achieve this, I've defined two CSS classes: .blur and .less-opacity CSS Stylesheet .blur { -webkit-filter: blur(10px); -moz-filter: blur(10px); -o-filter ...

Modifying the appearance of a Component within a NavLink

I'm currently working on a navbar using NavLink from React-Router-Dom. It's fine to use the 'isActive' prop to style the active Link, but I'm stuck on how to style the subelements inside it. For more specific details, please take a ...

Getting a 404 response for incorrect API URLs in ASP.NET Core and single-page applications

In order to properly handle incorrect API calls on the client side with Angular 5, I need to ensure that a 404 error is returned. Currently, the backend is returning a status code of 200 along with index.html, resulting in a JSON parse error on the fronten ...

Is there a way to adjust this validation logic so that it permits the entry of both regular characters and certain special characters?

Currently, the input field only accepts characters. If any other type of character is entered, an error will be thrown as shown in the code below. How can I update this logic to allow not only letters but also special characters like hyphens and apostrop ...

Failing Cypress component test: When leveraging an index.ts file for importing and exporting services

Tech stack: Angular v15 and Cypress v12. My example component that I'm testing: import { Component } from '@angular/core'; import { UserHttp } from '../../services'; @Component({ selector: 'example-view', templateUr ...

A unique Angular decorator is created to seamlessly integrate a new component within an existing component

I'm currently experimenting with creating a decorator in Angular that will display a spinner on top of the main component. Essentially, my main component is making API requests and I want to overlay the decorator on top of the method. This is how I ...

IE11 is throwing a fit because of a pesky long-running script error caused by the powerful combination of Webpack, React,

Utilizing webpack 4.* for bundling my react 16.* and typescript 3.* project has been causing issues on internet explorer 11. I consistently encounter a "not responding long running script error" on both local and test servers (in production mode). The lac ...

Although the cucumber tests indicate success, protractor fails to interact with the elements on the webpage

Recently, I delved into the realm of Protractor+Cucumber+Typescript and devised a sample framework utilizing Page Object Design along with a small script to execute some click actions. URL: My endeavor to click on the "Customer Login" button seems futile ...

Can someone help me understand why these checkboxes are not properly binding with the two-way binding, even though the opt.checked property is set to true?

<div style="display: table-caption" [id]="question.key" *ngSwitchCase="'checkbox'"> <div *ngFor="let opt of question.options; let i = index" style="display: flex; flex-directi ...