How to create a Dictionary with Key/Value pairs in angular?
Courtesy from Konrad Rudolph answer
Dictionary
is the “correct” name of the interface (= the ADT), i.e. an associative container that maps (usually unique) keys to (not necessarily unique) values.To summarize: a dictionary is an ADT that maps keys to values. There are several possible implementations of this ADT, of which the hash table is one.
Hash
is a misnomer but in context it’s equivalent to a dictionary that is implemented in terms of a hash table.
Solution 1
Straight forward you can use Map type as recommendation
//Using Map
let map = new Map<string, string>();
map.set("PO1", "closed");
map.set("PO2", "pending_approval");
map.set("PO3", "open");
map.set("PO4", "Draft");
map.set("PO5", "Cancelled");
map.set("PO6", "Rejected");
map.set("PO7", "Saved");
//get item
console.log(map.get('PO1'));
console.log(map.get('PO5'));
//has item
console.log(map.has('PO1'));
console.log(map.has('PO5'));
//delete item
console.log(map.delete('PO1'));
console.log(map.delete('PO5'));
Solution 2
But if you want custom additional methods you can also create a Dictionary implementation in typescript like as shown below
//Using Dictionary
let dict = new Dictionary();
dict.set("PO1", "closed");
dict.set("PO2", "pending_approval");
dict.set("PO3", "open");
dict.set("PO4", "Draft");
dict.set("PO5", "Cancelled");
dict.set("PO6", "Rejected");
dict.set("PO7", "Saved");
//get item
console.log(map.get('PO1'));
console.log(map.get('PO5'));
//has item
console.log(map.has('PO1'));
console.log(map.has('PO5'));
//delete item
console.log(map.delete('PO1'));
console.log(map.delete('PO5'));
dictionary.ts
export class Dictionary {
items = {};
constructor() {
this.items = {};
}
public has(key) {
return key in this.items;
}
public set(key,value) {
this.items[key] = value;
}
public get(key) {
return this.items[key];
}
public delete(key) {
if( this.has(key) ){
delete this.items[key]
return true;
}
return false;
}
}
Working Demo
A dictionary is a data type that maps from keys to values, and allows you to get the value for a given key in O(1) time.
In Typescript or Javascript, you can use an Object as a dictionary:
const dictionary = {
'key1': 'value1',
'key2': 'value2'
};
console.log(dictionary['key1']); // outputs 'value1'
You can also use the Map
type:
const map = new Map<string, number>();
map.set('key1', 100);
map.set('key2', 200);
console.log(map.get('key2')); // outputs 200