Add New Entries to Key Value Pair Array in Type Script

228 Views Asked by At

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?

2

There are 2 best solutions below

0
Andrew Shepherd On BEST ANSWER

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;
0
Robby Cornelissen On

That should just be:

dictionaryClass.Dictionary.ShowImage = false;

The forEach() function is used to iterate over arrays. You're dealing with an object instead of an array, and have no need to iterate.