Vienna Vienna - 1 year ago 66
Javascript Question

TypeScript: Using function parameter as JSON-key name

Following situation:

setFlags(data:any, key:string) {
this.flags.key= data;

assumed data is
{'foo': 'is cool'}
and key is
and the flags should look like:

'bar': {'foo': 'is cool'}

is there a any simple solution for that purpose?

EDIT: A reply to the questions in the comments: It is going about a TypeScriptClass which will be used as a service, that stores flags.

export class FormStoreService {
flags:any = {};
constructor() {}
setFlags(data:any, key:string) {
this.flags.key = data;

Answer Source

When you write, you are setting a property named bar. If the name of the property is dynamic, you should use the foo[bar] syntax. So the setFlags method becomes

setFlags(data:any, key:string) {
 this.flags[key] = data;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download