Create an object litteral containing properties from strings
How can I create an object evaluating the prop开发者_如何学Pythonerty names from variables?
For example:
I have the variable myString = 'aString'
And I want to create the object:
var obj = {
aString : "value";
}
And I want to use the variable myString
to create this.
The only solution I've come up with is something like this:
var string = '{"' + myString + '": value }';
var obj = $.parseJSON(string);
How can I make this more effective and cleaner?
var str = "key";
var obj = {};
obj[str] = "value";
You can access/set object properties like this :
var obj = {};
obj[mystring] = 'value';
精彩评论