开发者

Create an object litteral containing properties from strings

开发者 https://www.devze.com 2023-03-06 19:12 出处:网络
How can I create an object evaluating the prop开发者_如何学Pythonerty names from variables? For example:

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';
0

精彩评论

暂无评论...
验证码 换一张
取 消