Vienna Vienna - 4 months ago 12
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
'bar'
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.

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

Answer

When you write foo.bar, 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;
}
Comments