Problem
I am loading things from the localStorage
and this has to be saved as json, so it needs to have a simple Object
structure to be possible to JSON.parse()
.
However, som methods do not accept <any>
as parameter, because they want a concrete class
or interface
, but i want to send my object as parameter, so i have to convert it to a Map
in order to have the same structure, but seen as it has a type, it is now accepted as parameter.
My problem lies within the conversion from Object
to Map
Solution
public static convertObjectToMap<V>(obj: any, classOfV): Map<string, V> {
let objectMap = new Map<string, V>();
if (obj !== undefined && obj !== null) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const initObject = new classOfV(obj[key]);
objectMap.set(key, initObject);
}
}
}
return objectMap;
}
I take an obj
and the class
which all values are going to be in the same type.
Example of usage
//This is purely for the example
const fibonacciObject:any = {"0": 1, "1": 1, "2": 2, "3": 3, "4": 5};
const fibonacciMap:Map<string, Number> = convertObjectToMap<Number>(fibonacciObject, Number);
fibonacciMap.get("0"); //1
fibonacciMap.get("4"); //5
Question
Is there a better way to do this conversion, i know about new () => V
, but since i need it for each key, then it is not really feasible.
Also what Type would class
of V
be, i keep getting type errors when i try to give it a Type