Transform the data from a JSON object into an enum value

I am facing an issue where I need to convert a JSON string value into an enum to display a custom string on an HTML page. The error message states: Type '{ id: number; name: string; status: string; }[]' is not assignable to type 'Status[]'

Here is an example of the JSON record:

{ id: 1, name: 'Some name', status: 'STATUS01' },

In the file status.enum.ts, we have the following enum defined:

export enum Status {
  'STATUS01' = 'Operational',
  'STATUS02' = 'Some other status'
}

This enum is used in a model as shown below:

import { Status } from './status.enum';

export class ServiceState {
  id: number;
  name: string;
  status: Status;
}

Within the service, there is a function to retrieve all statuses (dummy data):

getStatuses(): Observable<ServiceState[]> {
    const response = [
      { id: 1, name: 'One', status: 'STATUS01' },
      { id: 2, name: 'Two', status: 'STATUS01' },
      { id: 3, name: 'OneTwo', status: 'STATUS02' },}
    ];
    return of(response);
  }

The current issue arises when trying to handle the return values.

Answer №1

It is recommended to utilize the enum values like this:

export enum Status {
  STATUS01 = 'Operational',
  STATUS02 = 'Some other status'
}

const response = [
  { id: 1, name: 'One', status: Status.STATUS01 },
  { id: 2, name: 'Two', status: Status.STATUS01 },
  { id: 3, name: 'OneTwo', status: Status.STATUS02 },
  // ...
];

To effectively map the enums' values:

getStatuses(): Observable<ServiceState[]> {
  const response = [
    { id: 1, name: 'One', status: 'STATUS01' },
    { id: 2, name: 'Two', status: 'STATUS01' },
    { id: 3, name: 'OneTwo', status: 'STATUS02' },
  ];

  return of(response).pipe(
    map((states) => states.map((state) => ({
      ...state,
      status: Status[state.status]
      } as ServiceState)
    )
  );
}

Answer №2

I'm still not clear on what you're asking, but it seems like you may need to align the API response with your class structure.

Solution

public retrieveStatus(): Observable<ServiceState[]> {
  return this.http.get('url').pipe(
    map(data => data.forEach(item => {
      item.status = Status[item.status];
    }))
  );
}

If you're only using the class for defining the type, consider using a simple interface instead.

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

Utilize Angular 17 to populate the date field in an edit form with saved data

I have a situation in my form where the date gets saved but it doesn't show up when I try to edit the form. Here is the JSON data: "checkOut": { "runDate": "2024-07-05T09:42:00.000Z", } The form input field looks li ...

a callback may seem like it's not a function, but in reality, it is

This question might seem simple, but I'm struggling to grasp the concept of callbacks, especially in NodeJS. My issue arises when trying to retrieve data from MySQL, something that is usually straightforward in most programming languages: In my rout ...

Exploring the world of two-dimensional arrays in D3 programming

I am interested in visualizing data obtained from the census data API, specifically from the ACS survey. The data is not in a typical JSON format, but rather as a two-dimensional array. It appears like this: [ [ “POPULATION”, “DATE”, ...

Remove specific data points from an array within a serialized post_meta in PHP

In my Wordpress setup, I have created a custom post type called "Artists"... There is a plugin that serializes the meta information from these Artists and I need to filter this data based on the channel value in the serialized meta key "show_data" ' ...

Encountering an error when attempting to access undefined property while using a method as a callback

Exploring OOP and angular is new to me. I am currently trying to implement a reusable table with pagination that triggers an API request when the page changes (pagination within the table component). The issue arises when I attempt to access my method usi ...

Different Ways to Remove an Element from an Array in TypeScript

I have been browsing through the responses here, but none of them seem to work for me. I am trying to remove an item from an array, but no matter what I do, the index keeps returning as -1. deleteItinerary(id: string) { this.dataSvc.removeItinerar ...

The argument labeled as 'Subscription' cannot be assigned to the parameter labeled as 'string' in Angular

I am utilizing my Subscription variables to retrieve the API from configuration settings. public ChannelsAPI=this._configservice.getConfiguration("ChannelAPI").subscribe((result) => console.log(result)); This is the method _Configservice.getC ...

Leveraging JSON within the store and forward mechanism of WSO2 ESB

Encountering an issue with JSON utilization within WSO2 ESB 4.9.1. Utilizing Builder org.apache.synapse.commons.json.JsonStreamBuilder Formatter org.apache.synapse.commons.json.JsonStreamFormatter in axis2.xml Implemented a Message Store and Message Proce ...

@vx/enhanced responsiveness with TypeScript

I am currently utilizing the @vx/responsive library in an attempt to retrieve the width of a parent component. Below are snippets from my code: import * as React from 'react' import { inject, observer } from 'mobx-react' import { IGlob ...

A guide on incorporating "this" keyword within a Mongoose UserSchema method using TypeScript

Currently, I am working on setting up a login API using Mongoose with TypeScript and JSON Web Token. As I am still new to TypeScript, I am facing an issue in the user.model file where I am unable to access any schema property using the "this" method. For e ...

Tips for dynamically binding the image source in Angular based on certain conditions

Hi, I'm receiving a response from an API that only includes a name but no image source. However, I have a collection of images in my local images folder. <div class="left"> <img src="{{ record.imgSrc }}" alt="{ ...

Difficulty locating the module in Typescript/Javascript

Currently facing an issue while trying to incorporate a module called "request" into my Angular 2 Typescript project from here. Despite following the usual installation process with npm install --save request and also attempting typings install request -- ...

Utilize mapping to object and preserve type inference

I am currently developing a function that utilizes a map function to map objects. interface Dictionary<T> { [key: string]: T; } function objectMap<TValue, TResult>( obj: Dictionary<TValue>, valSelector: (val: TValue) => TResult ...

Running the nx dep-graph command on certain projects can be accomplished by specifying the project names

Currently, I am involved in a project that utilizes a mono-repo structure. Our workspace is managed with Nx, where various feature-projects are loaded into a central portal application. I am interested in running a dependency graph analysis on a specific ...

An error was encountered with Ajax and JSONP due to an unexpected token causing a SyntaxError

Currently attempting to retrieve information from the host at 000webhost The data is in JSONP format: { "categories": { "category": [ { "name": "Android", "parent": "Computer Science", "ID": "2323" }, { ...

ngx-slick-carousel: a carousel that loops infinitely and adjusts responsively

I have implemented ngx-slick-carousel to showcase YouTube videos in my project. However, I am facing two main issues. Firstly, the carousel is not infinite, and when the last video is reached, there appears to be white spaces before it loops back to the fi ...

Guide to forming a nested JSON structure with specific key names in Python

I have some data stored in a pandas dataframe that I would like to organize by month and type. month hour Type count 0 4 0 Bike 8 1 4 0 Pedelec 16 2 4 1 Bike 9 3 4 1 Pedelec 4 4 4 2 Bike 18 ... ... ... ... ... ...

What is the best way to divide a string that contains n concatenated JSON strings in JavaScript or Node.js?

Imagine I receive the following string from a socket server (which is out of my control): {"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}} Because it contains 2 JSON strings, using ...

Update the regular expression pattern to extract nested tags and store them in an array of objects

For my small application, I am working on creating a regex pattern to identify "faux" html tags. The goal is to capture these tags within curly brackets and output them into an array of objects. Below is the code snippet with the current regex pattern: { ...

What is the process for decoding data into an embedded struct?

Is there a way to utilize .Decode() on a response body to populate a struct without needing to determine the specific type of struct beforehand? I have a versatile struct called Match, designed to store information about various games, like a match in For ...