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 –
JavaScript
x
6
1
export enum Status {
2
HIGH = "High",
3
MEDIUM = "Medium",
4
LOW = "Low"
5
}
6
My model –
JavaScript
1
9
1
import { Status } from "../enums/status.enum";
2
3
export class OrderModel {
4
id: number;
5
notification: string;
6
action: string;
7
status: Status ;
8
}
9
My json –
JavaScript
1
9
1
[
2
{
3
"id": 1,
4
"notification": "Order has ben packed",
5
"action": "Assign to delivery",
6
"status": "High"
7
}
8
]
9
Here I am trying to map the JSON to my model but getting the error (Type ‘string’ is not assignable to type ‘Status’) –
JavaScript
1
18
18
1
import { OrderModel } from '../../models/order.model';
2
import orderData from '../json/order.json';
3
4
@Injectable({
5
providedIn: 'root'
6
})
7
export class OrderService{
8
9
//Here mapping JSON data to my model
10
orderModel: OrderModel[] = orderData;
11
12
constructor() {}
13
14
getOrderStatus() {
15
console.log(orderModel)
16
}
17
}
18
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.
JavaScript
1
5
1
orderModel: OrderModel[] = orderData.map(e => ({
2
e,
3
status: Status[e.status],
4
}));
5