I've got a problem with initialize an arrays of map objects in my typescript interface like below:
interface SomeInterface{
id: string,
types: Array<Map<string, number>>;
}
I need to create object with field types as an array which will be hold many of map with string and number. I want this, but i don't know how to add new map into this array.
I try even in this way but it not work and types is still an empty object:
const t: Array<Map<string, number>> = new Array<Map<string, number>>();
const map = new Map<string, number>();
t.push(map.set("test1", 2));
t.push(map.set("test2", 5));
const a: SomeInterface= {
id: "test",
types: t
}
console.log(a);
//{
// "id": "test",
// "types": [
// {},
// {}
// ]
//}
Can someone tell me how to add new map into an typescript array?
thanks for any help!
CodePudding user response:
According to your code I would do something like following
const t: Array<Map<string, number>> = new Array<Map<string, number>>();
t.push(new Map([["test1", 2]]));
t.push(new Map([["test12", 5]]));
CodePudding user response:
Here's an example showing how you can:
- create an array of maps
- create a new map
- set items in the map
- push the map into the array
const arrayOfMaps: Array<Map<string, number>> = [];
// create a map
const map1 = new Map<string, number>();
// add entries to the map
map1.set("test1", 1);
map1.set("test2", 2);
// insert the map at the end of the array
arrayOfMaps.push(map1);
console.log(arrayOfMaps); // [Map (2) {"test1" => 1, "test2" => 2}]
const firstMapInArray = arrayOfMaps[0];
console.log(firstMapInArray); // Map (2) {"test1" => 1, "test2" => 2}
console.log(firstMapInArray === map1); // true
