2016-12-05 449 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

相關問題