Develop a versatile class for storing an array of key-value pairs (dictionary) using TypeScript

I am looking to implement a Dictionary class in my application. I have created a class with an Array of KeyValuePair to store my list.

export class KeyValuePair<TKey, TVal>{
key:TKey;
value:TVal;

constructor(key:TKey, val:TVal){
    this.key = key;
    this.value = val;
}

export class Dictionary<TKey, TVal>{
    array: Array<KeyValuePair<TKey, TVal>>
}

let myClassInstance:Dictionary<number, string> = ...;

Some Questions:

  1. I want to be able to iterate through it using forEach or in a loop like 'let x of myClasInstance', how can I achieve this? (myClassInstance.forEach(...);)
  2. Can I access the array in the class instance without referring to className.arrayName directly? (myClassInstance.find(...);)
  3. Is it possible to use the class instance as an index to retrieve values? (myClassInstance[1])
  • If there is a better structure for this implementation, I would love to hear and learn about it. Thank you!!!

Answer №1

Discover the wonders of Maps, which are like dictionaries in JavaScript.

You can utilize Maps effectively by visiting this Playground.

You can easily iterate through their values, keys, or entries with typed results. Need to find something? Just use get. And if you need them as arrays, simply convert with [...myMap.values()], keeping in mind they will be ordered based on key insertion. (or use entries() and map for custom sorting)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Organize Dates in React Table

I need help with sorting the Date column in my code. Currently, the sorting is being done alphabetically. Here is the JSON data and code snippet: JSON [ { "date": "Jun-2022" }, { "date": "Jul-2022" } ...

Refine specific unions by considering past values that have been used

Here's the scenario at hand: type Option = 'x' | 'y' | 'z' | 'w' type Inquiry = { query: string; choices: Option[]; defaultChoice: Option // here's where it gets tricky } I am looking to set the def ...

Playwright script encounters module not found error

I am currently facing an issue with implementing Playwright in my project. It seems that Playwright is struggling to a) resolve path aliases and b) it is unable to locate certain npm packages that have been installed. Here is the structure of my project: ...

Guide on categorizing MUI icon types

My current code snippet is as follows: type MenuItem = { key: string; order: number; text: string; icon: typeof SvgIcon; }; However, when I attempt to use it in my JSX like this: <List> {MENU.map((menuItem: MenuItem) => ( ...

Creating a blank webpage after including a component tag for an Angular form

I encountered an issue while developing an Angular form. It seems that using the app-name-editor tag causes my entire HTML page to go blank, and the form does not display. However, removing the tag restores the webpage's functionality. This leads me t ...

Protected HTTP Live Streaming 128-bit AES encryption key location

After encrypting a video using HLS AES-128 with the apple tool, I have generated an m3u8 file that looks like this: #EXTM3U #EXT-X-TARGETDURATION:10 #EXT-X-MEDIA-SEQUENCE:0 #EXT-X-PLAYLIST-TYPE:VOD #EXT-X-KEY:METHOD=AES-128,URI="https://xxxxx.com/api/ ...

The formBuilder validator pattern seems to be malfunctioning

I am attempting to display a message when the password does not meet the formGroup pattern. Here is how my FormGroup is initialized: this.signupForm = fb.group({ userName: ['', Validators.compose([Validators.required,Validators.pattern(/^&bsol ...

Issue with @Input causing detectChanges error in Angular 6 unit testing

A basic component is utilized to accept a configuration object as an input and utilize it to initialize certain values in the ngOnInit lifecycle hook. export class MyComponent implements OnInit { @input() config: ConfigObject; min: number; max ...

Encountering CORS Error: Challenge in sending post requests with NodeJs and Angular

Whenever I attempt to make a post request, I encounter the following error message: Access to XMLHttpRequest at 'http://localhost:3002/api/products/checkout' from origin 'http://localhost:4200' has been blocked by CORS policy: Request ...

Building a personalized React component poses challenges when working with MUI REACT interfaces

I am looking to develop a unique component that will display two different elements, an icon, and a title. However, I seem to be encountering errors from TypeScript regarding the declaration of my interface. The error message reads: Property 'map&apos ...

Identifying property changes in Angular: A step-by-step guide

I am working with a component that includes a sub component called timeline. <app-timeline [(editing)]="editingDate"></app-timeline> Within the timeline component, there are specific properties: @Input() editing: boolean; // <--- monitor ...

Angular 2 is throwing an error, stating that Observable is not defined

I'm currently working with Observable and ChangeDetectionStrategy to notify other components about any changes that occur. However, I am encountering an issue where the Observable object addItemStream is coming up as undefined. Can anyone spot what mi ...

HttpErrorResponse: unexpected internal server error

Just getting started with Angular 6. I created a post service using Spring Boot, and it works perfectly when tested with Postman. But testing it in a web browser results in the following error: HttpErrorResponse {headers: HttpHeaders, status: 500, statusT ...

Is there a way to manipulate data being passed to a subject.next() in RXJS before emitting it again?

I have a feeling that this question is going to reveal some gaps in my understanding of observables, but I'll ask it anyway. I want to create an RXJS subject that performs operations on the data before emitting it again. Let me explain with a simple ...

Troubleshooting Angular Unit Tests: Issues with Observable Response

Currently, I am working on an Angular application that is a bit dated and I am in the process of unit testing to ensure that all functions are operating as intended. Specifically, my focus is on testing whether a function correctly returns the expected ht ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...

Preventing memory leaks in unmounted components: A guide

Currently, I am facing an issue while fetching and inserting data using axios in my useState hook. The fetched data needs to be stored as an array, but unfortunately, I encountered a memory leak error. I have tried various solutions including using clean u ...

Submitting an image blob to a database using the FormBuilder

I'm facing an issue with uploading a file blob into the same DB as my form. Here is my form: this.accForm = this.formBuilder.group({ team_leader: ['', Validators.required], hotel_name: ['', Validators.required], address: [&a ...

Strategies for extracting the type argument from a nested property and transforming it into a different value

I’m struggling to find the right way to frame my question, so I’ll provide an example of what I need help with. Let's assume I have the following object: const obj = { one: 'some string', two: new Set<string>(), }; Now, I wan ...

What are the ways to recognize various styles of handlebar designs?

Within my project, I have multiple html files serving as templates for various email messages such as email verification and password reset. I am looking to precompile these templates so that they can be easily utilized in the appropriate situations. For ...