Skip to content
Advertisement

Angular: How to map string to enum

I am trying to map list of JSON to my model but one of my model property is enum but from the JSON I am getting that property as a sting so, how can map that string as a enum

My enum –

export enum Status {
  HIGH = "High",
  MEDIUM = "Medium",
  LOW = "Low"
}

My model –

import { Status } from "../enums/status.enum";

export class OrderModel {
  id: number;
  notification: string;
  action: string;
  status: Status ;
}

My json –

[
 {
   "id": 1,
   "notification": "Order has ben packed",
   "action": "Assign to delivery",
   "status": "High"
 }
]

Here I am trying to map the JSON to my model but getting the error (Type ‘string’ is not assignable to type ‘Status’) –

import { OrderModel } from '../../models/order.model';
import orderData from '../json/order.json';

@Injectable({
  providedIn: 'root'
})
export class OrderService{

//Here mapping JSON data to my model
orderModel: OrderModel[] = orderData;

constructor() {}

getOrderStatus() {
 console.log(orderModel)
 }
}

Advertisement

Answer

You’ll need to mutate your incoming model to get the enum key. Interesting thing about TypeScript enums is that they are reverse-mappable. Therefore if you map your incoming data to your actual class you can use the value to look up the enum key.

orderModel: OrderModel[] = orderData.map(e => ({
  ...e,
  status: Status[e.status],
}));
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement