let myObject : IHash = {};
myObject['name'] = 'John';
myObject['age'] = 25;
console.log(myObject['name']);
// results in John
console.log(myObject['age']);
// results in 25
If you wish to loop through your dictionary, you can use the following method.
Object.keys(myObject).forEach((key) => {console.log(myObject[key])});
The Object.keys function retrieves all properties of an object, making it suitable for returning values from dictionary-like objects.
You mentioned a hashmap in your query; the definition provided is for a dictionary-style interface where keys are unique but not values.
To treat it like a hashset, assign the same value to both key and value fields.
If you want unique keys with potentially different values, verify if the key exists before adding it.
let newValue = 'apple';
if(!myObject[newValue])
myObject[newValue] = newValue;
Alternatively, create a custom class to serve as a hashset.
Class MyHashSet{
private var keys: IHash = {};
private var values: string[] = [];
public addKey(key: string){
if(!keys[key]){
values.push(key);
keys[key] = key;
}
}
public getValues(){
// Copying the array prevents accidental alterations by users
return values.slice();
}
}