JavaScript set object key by variable [duplicate]

2018-12-31 08:13发布

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:

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?

Fiddle for better explanation: http://jsfiddle.net/Fr6eY/3/

标签: javascript
2条回答
永恒的永恒
2楼-- · 2018-12-31 08:51

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:

If you're able to use ES6 and Babel, you can use this new feature:

{
    [yourKeyVariable]: someValueArray,
}  
查看更多
看风景的人
3楼-- · 2018-12-31 08:56

Try something like this (check ES6 example at the end of answer)

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"}

In ES6, you can do like this.

var key = "name";
var person = {[key]:"John"};
console.log(person); // should print  Object { name="John"}

    var key = "name";
    var person = {[key]:"John"};
    console.log(person); // should print  Object { name="John"}

查看更多
登录 后发表回答