In my angular2 app i want to create a map which takes a number as key and returns an array of objects. I am currently implementing in following way but no luck. How should i implement it or should i use some other data structure for this purpose? I want to use map because maybe its fast?

Declaration

 private myarray : [{productId : number , price : number , discount : number}];

priceListMap : Map<number, [{productId : number , price : number , discount : number}]> 
= new Map<number, [{productId : number , price : number , discount : number}]>();

Usage

this.myarray.push({productId : 1 , price : 100 , discount : 10});
this.myarray.push({productId : 2 , price : 200 , discount : 20});
this.myarray.push({productId : 3 , price : 300 , discount : 30});
this.priceListMap.set(1 , this.myarray);
this.myarray = null;

this.myarray.push({productId : 1 , price : 400 , discount : 10});
this.myarray.push({productId : 2 , price : 500 , discount : 20});
this.myarray.push({productId : 3 , price : 600 , discount : 30});
this.priceListMap.set(2 , this.myarray);
this.myarray = null;

this.myarray.push({productId : 1 , price : 700 , discount : 10});
this.myarray.push({productId : 2 , price : 800 , discount : 20});
this.myarray.push({productId : 3 , price : 900 , discount : 30});
this.priceListMap.set(3 , this.myarray);
this.myarray = null;

I want to get an array of 3 objects if i use this.priceList.get(1);

推荐答案

首先,为您的对象定义一个类型或接口,它将使内容更具可读性:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

Json相关问答推荐

时间和日期数据绘制不正确

Google Page to JSON应用程序脚本出现CORS错误

在T—SQL中将STR_AGG与JSON_ARRAY结合起来

Golang JSON Date Tim.Date()测试请求

与错误相关的未定义&Quot;不是有效的JSON

Postgres Select json数组并重新映射属性名称

如何避免解析 ISuperObject 类型字段中的 json 对象

使用 Redis 作为键值存储

使用jq根据对象中键的值查找对象

NiFi 使用嵌套数组将 avro 转换为 JSON 数组格式

添加到数组时出错:找不到Add的重载和参数计数:1

JOLT 在 struct 体中间添加一个 JSON 字段

JQ 中的样本标准偏差

如果 jq 数组中的字符串是对象或字符串,则获取值

使用 @ResponseBody 自定义 HttpMessageConverter 来做 Json 事情

如何从 mysql 数据库构建 JSON 数组

在 Rails 3 中处理 JS/ERB 模板中的 JSON

JSON Schema:验证数字或空值

Django:TypeError:[] 不是 JSON 可序列化的为什么?

未调用 npm package.json 脚本