繁体   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