ChatGPT解决这个技术问题 Extra ChatGPT

JavaScript set object key by variable

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/

The solution in ES6 is to put the variable in square brackets in order to evaluate it. var key = "happyCount"; myArray.push({ [key]: someValueArray });
@Jake The only browser that currently does not support this es6 feature is IE11: kangax.github.io/compat-table/es6/…
@Jake That's a good point. One possible solution is to use babel to transpile ES6 into ES5.
@Jake That is exactly what babel is for. As Dan Cron mentions above.
@Jake Like Hunter says, it's best not to code for ES5 users. If you need to support older browsers, pollyfill & transpile. It's now 2018, not 2009, we really need to move on.

g
gen_Eric

You need to make the object first, then use [] to set it.

var key = "happyCount";
var obj = {};

obj[key] = someValueArray;
myArray.push(obj);

UPDATE 2021:

Computed property names feature was introduced in ECMAScript 2015 (ES6) that allows you to dynamically compute the names of the object properties in JavaScript object literal notation.

const yourKeyVariable = "happyCount";
const someValueArray= [...];

const obj = {
    [yourKeyVariable]: someValueArray,
}

@AlexG: It was used in the question.
Note, that things changed for the better in ES6, i.e. {[key]:someValueArray}
@Frank Nocke I'm looking forward to be able to use it in about 10 years time when all the 'browsers' we have to support support it...
@Jake you can program in ES6 or ES7 today, and have Babel compile your JS file back to ES5. This is how webapps are built nowadays.
for those who wonder how this ES6 feature is called: it is Computed property name
k
kiranvj

In ES6, you can do like this.

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 }

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.

For ES5, try something like this

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


I provided a solution that I think may be of some interest to people at this link using underscore: stackoverflow.com/questions/5640988/…
d
devtunus

Use this.

var key = 'a'
var val = 'b'

console.log({[key]:val})

//a:'b'

This answer was already given by @kiranvj
I do like how I can get the answer very quickly, as opposed to @kiranvjs answer