How to define Typescript Map of key value pair. where key is a number and value is an array of objects

后端 未结 3 2061
广开言路
广开言路 2021-01-30 20:41

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 imp

相关标签:
3条回答
  • 2021-01-30 20:56

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

    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;
    

    (code in playground)

    0 讨论(0)
  • 2021-01-30 21:02

    The most simple way is to use Record type Record<number, productDetails >

    interface productDetails {
       productId : number , 
       price : number , 
       discount : number
    };
    
    const myVar : Record<number, productDetails> = {
       1: {
           productId : number , 
           price : number , 
           discount : number
       }
    }
    
    0 讨论(0)
  • 2021-01-30 21:13

    you can also skip creating dictionary altogether. i used below approach to same problem .

     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}));
            }
        });
    
    0 讨论(0)
提交回复
热议问题