A quick introduction to Dictionary or Map Object. In a nutshell, it is used to manage key-value pairs.
Below is the primary usage of Map Object.
First, we are going to use the MODEL below as an example for storing our values.
Then we will use a Class as a SERVICE to manage our Map Object.
To add a record in our Map Object:
To delete a record in our Map Object:
To get a value in our Map Object:
To get the keys in our Map Object:
To get the key-value pairs in our Map Object:
To get the values in our Map Object:
To get the length or size of our Map Object:
That sums up the usage. Pretty simple, right?
Now we can use it in our Angular component like the code snippet below.
So what are the ADVANTAGES of using it?
- Easy to manage, delete, update, or get a record
- No need to use an index to do something with the record
- Prevents Object Injection Attack
- Convertible to Array
- Uses Iterable by default
- Iterable can be used directly in the *ngFor directive of Angular
Make sure the downlevelIteration is enabled in your tsconfig file
Let's expose the values as IterableIterator in our SERVICE
Let's add a Person to our Map Object and use the Iterable values in our Angular template
This is how to use the Iterable values in our Angular template, just similar to how we loop the normal Array
How about sorting the key-value pairs?
Currently, it is not supported in the Map Object itself but below is a workaround to sort the key-value pairs.
Let's add a sort method to our SERVICE. We have to clear our Map Object and reinsert the key-value pairs
Then let's add more values in our Map Object and call the sort method that we just added in our SERVICE
Finally, this will be our output after sorting
We can just use the normal Array to sort, so we don't need to reset our Map Object.
Thanks for reading! Don't forget to subscribe if you want more updates! 😉
Top comments (0)