programing

키 값 쌍의 유형 스크립트 맵을 정의하는 방법.여기서 key는 숫자이고 value는 개체의 배열입니다.

javamemo 2023. 3. 26. 09:18
반응형

키 값 쌍의 유형 스크립트 맵을 정의하는 방법.여기서 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;

사용할 경우 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;

(운동장 코드)

가장 간단한 방법은 활자를 사용하는 것입니다.Record<number, productDetails>

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

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

당신은 또한 사전을 만드는 것을 모두 생략할 수 있습니다. 나는 같은 문제에 대한 아래 접근법을 사용했습니다.

     mappedItems: {};
     items.forEach(item => {     
            if (!mappedItems[item.key]) {
              mappedItems[item.key] = [];
            }
            mappedItems[item.key].push({productId : item.productId , price : item.price , discount : item.discount}));
        });

언급URL : https://stackoverflow.com/questions/40976536/how-to-define-typescript-map-of-key-value-pair-where-key-is-a-number-and-value

반응형