如何定义键值对的Typescript映射.其中key是一个数字,value是一个对象数组 [英] How to define Typescript Map of key value pair. where key is a number and value is an array of objects

查看:765
本文介绍了如何定义键值对的Typescript映射.其中key是一个数字,value是一个对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的angular2应用程序中,我想创建一个以数字为键并返回对象数组的地图.我目前正在以以下方式实施,但没有运气.我应该如何实现它,或者应该为此目的使用其他一些数据结构?我想使用地图,因为它可能很快?

In my angular2 app i want to create a map which takes a number as key and returns an array of objects. I am currently implementing in following way but no luck. How should i implement it or should i use some other data structure for this purpose? I want to use map because maybe its fast?

声明

 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);

推荐答案

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

First thing, define a type or interface for your object, it will make things much more readable:

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

您使用的是尺寸为1而不是数组的一个元组 ,它应该看起来像这样:

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

所以现在可以正常工作了:

So now this works fine:

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;

( 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆