ForEach with Typescript-Collection

Hi all,

I guess I have an easy question, but where I couldn’t find a good solution for.
I’m using typescript-collections:

let testCollection = Collections.Dictionary<string, Collection<string, string>();

Now I want to iterate all elements. For that, the collection provides a foreach-method. But I don’t have any idea how I can get the key and value within the foreach method:

testCollection.foreach(element => {
    let key: string = ???
    let value: Collection.Dictionary<string, string> = ???
})

Can anyone help me?

from their code

   forEach(callback: (key: K, value: V) => any): void 

so this should work:

testCollection.foreach((key:string,value:string)=> {
console.log(key, value);
})
1 Like

On another note, you can define dictionaries without any third party libraries.

//define
const dict: { [index:string]: string} = {};
//set
dict["key"] = "value"
//remove
delete dict["key"];
dict["key1"]="value1";
dict["key2"]="value2";
//loop
Object.keys(dict).forEach(key=> {
  console.log(`key:${key}`, `val:${dict[key]}`);
});
//key check
if(dict.hasOwnproperty("key2")){
  console.log("dict has key2");
}
1 Like

One additional question…
How do you recommend to set the method parameter expecting that kind of collection?

myMethod(testCollection: ???){}

Would you set the type to any?

I would avoid any until it becomes too troublesome.
Looking at the source it should just be
myMethod(testCollection: Dictionary<string, string>){}