1

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)
 }
}

1 Answer 1

1

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],
}));
Sign up to request clarification or add additional context in comments.

6 Comments

@C.Das glad to hear it - don't forget to upvote/mark answer please.
Hi @McAden, although this is working and it is not throwing any error but my 'status' property is coming as undefined, any idea?
Always? or sometimes?
Always except the 'property' I am getting the data for all other fields
That doesn't make sense unless your data is invalid - especially since your initial comment said it was working
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.