typescriptdictionarykeyvaluepair

Add New Entries to Key Value Pair Array in Type Script


I am trying to add a new key value pair entry to the existing dictionary. Here's the TypeScript to define the dictionary:

export class DictionaryClass {
    Dictionary?: { [key: string]: boolean };
}

export function getDictionary(locale: string) {

let dictionaryClass = new DictionaryClass();
dictionaryClass.Dictionary = {
 "ShowButton": true
};
dictionaryClass.Dictionary.forEach(v => { "ShowImage": false; });

return dictionaryClass;

}

I googled around and I was told ForEach would be the method to add new entries, but it doesn't seem to have such method.

Any other idea to approach this?


Solution

  • If you know the key in advance:

    dictionaryClass.Dictionary.ShowImage = false;
    

    If you don't know the key in advance, you can reference the key using square brackets:

    let k:string = 'ShowImage'; // Or any value
    dictionaryClass.Dictionary[k] = false;