JavaScript 通过变量设置对象键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11508463/
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
JavaScript set object key by variable
提问by Hunter McMillen
I am building some objects in JavaScript and pushing those objects into an array, I am storing the key I want to use in a variable then creating my objects like so:
我正在用 JavaScript 构建一些对象并将这些对象推送到一个数组中,我将要使用的密钥存储在一个变量中,然后像这样创建我的对象:
var key = "happyCount";
myArray.push( { key : someValueArray } );
but when I try to examine my array of objects for every object the key is "key"
instead of the value of the variable key. Is there any way to set the value of the key from a variable?
但是当我尝试检查每个对象的对象数组时,键"key"
不是变量键的值。有没有办法从变量中设置键的值?
Fiddle for better explanation: http://jsfiddle.net/Fr6eY/3/
小提琴更好的解释:http: //jsfiddle.net/Fr6eY/3/
回答by Rocket Hazmat
You need to make the object first, then use []
to set it.
您需要先制作对象,然后使用[]
来设置它。
var key = "happyCount";
var obj = {};
obj[key] = someValueArray;
myArray.push(obj);
UPDATE 2018:
2018 年更新:
If you're able to use ES6and Babel, you can use this new feature:
如果你能够使用ES6和Babel,你可以使用这个新特性:
{
[yourKeyVariable]: someValueArray,
}
回答by kiranvj
In ES6, you can do like this.
在 ES6 中,你可以这样做。
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";
var person = {[key]:"John"};
console.log(person); // should print Object { name="John"}
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
它称为计算属性名称,它使用括号表示法(方括号)实现 []
Example: { [variableName] : someValue }
例子: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.
从 ECMAScript 2015 开始,对象初始值设定项语法也支持计算属性名称。这允许您将表达式放在括号 [] 中,该表达式将被计算并用作属性名称。
For ES5, try something like this
对于 ES5,尝试这样的事情
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
例子:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}