Reputation: 879
I need to change a value from a object. In javascript I would do something like
data = {};
this.data.password = this.password;
What can I do to change or maybe to add a new key/value to this object?
Upvotes: 1
Views: 24476
Reputation: 4172
You could also use the bracket syntax to specify keys of objects like so:
this.data["password"] = this.password;
This is quite useful, especially when you need to set an object's key as the value of some other variable.
Since we're dealing with TypeScript, the "proper" way would probably be to specify the type of this.data.
For example, you could set up an interface and then let the IDE/compiler know that this.data has a password property:
interface MyData {
password: string;
}
let data:MyData = {};
this.data.password = this.password;
Another (faster, yet slightly more technical-debt-creating) way you could solve it is to just give data the type of any.
let data:any = {};
this.data.password = this.password;
And as you've noticed you could also give it the type Object since this is sort of a special type that allows you to assign any property on it (for more info see this TypeScript Basic Types docs page).
Happy coding!
Upvotes: 8
Reputation: 879
That worked when I changed the declaration to
data : Object;
Now I can do
this.data.password = this.password;
Upvotes: 1