Javascript 将字符串值转换为对象属性名称
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12164764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string value to object property name
提问by Michael Broschat
Possible Duplicate:
How to convert string as object's field name in javascript
I can do this:
我可以做这个:
var objPosition = {};
objPosition.title = "whatever";
But I'm getting 'title' dynamically, and want to use about a half dozen strings so obtained to assign the half dozen properties to the object. I've tried eval and several other schemes that seem to have the same problem, but have come up empty so far.
但是我正在动态获取“标题”,并且想要使用大约六个这样获得的字符串来将六个属性分配给对象。我试过 eval 和其他几个似乎有同样问题的方案,但到目前为止都是空的。
I have:
我有:
var txtCol = $(this).text();
txtCol = $.trim(txtCol);
and I want the value of txtCol to be a property name.
我希望 txtCol 的值是一个属性名称。
Any ideas?
有任何想法吗?
回答by mellamokb
回答by KooiInc
use bracket notation: objPosition['title'] = "whatever";
使用括号表示法:objPosition['title'] = "whatever";
so:
所以:
var objPosition = {}, ttl = 'title';
objPosition[ttl] = 'whatever';
[edit 11/2019: es20xx]
[编辑 11/2019:es20xx]
let objPosition = {};
const ttl = 'title';
// [...]
objPosition = {...objPosition, [ttl]: "whatever"};
console.log(objPosition);
回答by Shreedhar
you can also set the object's key like this
你也可以像这样设置对象的键
var property = "title"
objPosition[property] = "something";
回答by Some Guy
Use the bracket notation like this:
像这样使用括号表示法:
objPosition["title"] = "Whatever";