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

标签 arrays json angular typescript

在我的 angular2 应用程序中,我想创建一个以数字为键并返回对象数组的映射。我目前正在以下列方式实现,但没有运气。我应该如何实现它或者我应该为此目的使用其他一些数据结构?我想使用 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);

,我想获得一个包含 3 个对象的数组

最佳答案

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

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

您使用了 a tuple大小为 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;

( code in playground )

关于arrays - 如何定义键值对的 Typescript Map。其中key是一个数字,value是一个对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40976536/

相关文章:

java - 将 JSON 分配给 Java String 时如何转义特殊字符

angular - 如何在 Angular 2最终版本的路由之间传递数据对象

angular - 创建类以在 Angular 4 中保存所有自定义验证的正确方法

python - Numpy:计算所有行 i 的 sum(array[i, a[i]:b[i]])

c - 为什么没有打印任何内容? C语言编程

javascript - Ajax 请求返回 200 OK,但会触发错误事件而不是成功

android - Json不能转int

html - Angular 2 - 单击div后更改视频src

php - 取消数组中键的范围

c - 如何在 C 中不使用 malloc() 来声明带有变量的数组?