Search This Blog

Monday, March 5, 2018

How to transform a Array to a map in Javascript/Typescript

This might be an easy one but I thought it is worth saving it here.
Let's assume you want to create a HashMap in typescript or javascript with http status codes and corresponding messages. This might be useful within a frontend error handler.
Here is your error-messages.json


[
  {"code": 403,    "message": "You are not permitted to use this action."  },
  {"code": 400,    "message": "The request was incomplete or wrong."  }, 
  {"code": 500,    "message": "A general error has occured."  }
]

here is how you could use it in your code:


// Map with error codes
  errorCodeMapping: Map<number, string> = new Map<number, string>();
// read error codes as json map
let array = Array.from(require("./error-messages.json"));
// map array to errorCode Map
this.errorCodeMapping = new Map(array.map((i: ErrorMessage): [number, string] => [i.code, i.message]));
// get a message for an error code
let msg: string = this.errorCodeMapping.get(403);

No comments:

Post a Comment