如何定义键值对的Typescript Map.其中key是数字,value是对象数组

usm*_*ana 38 arrays json typescript angular

在我的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}]>();
Run Code Online (Sandbox Code Playgroud)

用法

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;
Run Code Online (Sandbox Code Playgroud)

如果我使用,我想获得一个包含3个对象的数组 this.priceList.get(1);

Nit*_*mer 64

首先,为对象定义类型或接口,它将使事物更具可读性:

type Product = { productId: number; price: number; discount: number };
Run Code Online (Sandbox Code Playgroud)

您使用了一个大小为1 的元组而不是数组,它应该如下所示:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();
Run Code Online (Sandbox Code Playgroud)

所以现在这很好用:

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;
Run Code Online (Sandbox Code Playgroud)

(游乐场代码)


kum*_*etu 7

您也可以完全跳过创建字典。我用下面的方法来解决同样的问题。

 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}));
        }
    });
Run Code Online (Sandbox Code Playgroud)


aWe*_*per 6

最简单的方法是使用Record类型Record<number, productDetails>

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

const myVar : Record<number, productDetails> = {
   1: {
       productId : number , 
       price : number , 
       discount : number
   }
}
Run Code Online (Sandbox Code Playgroud)