2016-12-05 85 views
15

在我的angular2应用程序中,我想创建一个以数字为键并返回对象数组的映射。我目前正在实施以下方式,但没有运气。我应该如何实现它,或者我应该使用其他一些数据结构来达到这个目的吗?我想使用地图,因为它可能很快?如何定义键值对的Typescript Map。其中键是一个数字,值是一个对象数组

宣言

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}]>(); 

使用

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; 

我想如果我使用this.priceList.get(1);

回答

23

首先要获得3个对象的数组,定义一个类或接口你的对象,它会使事情变得更加可读:

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

您使用的大小而不是一个阵列的a tuple,它应该是这样的:

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

所以现在这工作得很好:

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

+0

在你的操场链接在控制台中有一个错误Uncaught TypeError:无法读取未定义(...)的属性“推”我实施它使用一个接口,我得到了同样的错误。 – usmanwalana

+1

这是因为我刚刚复制了你的代码,并且在你的代码中你将'myarray'设置为null,然后尝试推送它。所以要么不要将它设置为null,要么稍后再重新分配一个新的数组。 –

+0

谢谢。这工作。 – usmanwalana

相关问题