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

新手上路,请多包涵

在我的 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 个对象的数组

原文由 usmanwalana 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

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

 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;

操场上的代码

原文由 Nitzan Tomer 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

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

原文由 aWebDeveloper 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏