簡體   English   中英

如何定義鍵值對的 Typescript Map。 其中鍵是一個數字,值是一個對象數組

[英]How to define Typescript Map of key value pair. where key is a number and value is an array of objects

在我的 angular2 應用程序中,我想創建一個以數字為鍵並返回一個對象數組的地圖。 我目前正在按以下方式實施,但沒有運氣。 我應該如何實現它還是應該為此使用其他一些數據結構? 我想使用地圖,因為它可能很快?

聲明

 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);我想得到一個包含 3 個對象的數組this.priceList.get(1);

首先,為你的對象定義一個類型或接口,它會讓事情變得更具可讀性:

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

您使用大小為 1 的元組而不是數組,它應該如下所示:

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;

操場上的代碼

您也可以完全跳過創建字典。 我用下面的方法來解決同樣的問題。

 mappedItems: {};
 items.forEach(item => {     
        if (mappedItems[item.key]) {
           mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount});
        } else {
          mappedItems[item.key] = [];
          mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        }
    });

最簡單的方法是使用Record類型Record<number, productDetails>

interface productDetails {
   productId : number , 
   price : number , 
   discount : number
};

const myVar : Record<number, productDetails> = {
   1: {
       productId : number , 
       price : number , 
       discount : number
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM