1427

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/

t.niese
  • 36,631
  • 8
  • 65
  • 95
Hunter McMillen
  • 56,682
  • 21
  • 115
  • 164
  • 559
    The solution in ES6 is to put the variable in square brackets in order to evaluate it. `var key = "happyCount"; myArray.push({ [key]: someValueArray });` – Dan Cron Apr 29 '16 at 20:40
  • @DanCron Sounds great, but when will 99%+ of 'browsers' in the user base be ES6-capable? – Jake Sep 28 '17 at 07:09
  • 8
    @Jake The only browser that currently does not support this es6 feature is IE11: https://kangax.github.io/compat-table/es6/#test-object_literal_extensions_computed_properties – Hunter McMillen Sep 28 '17 at 13:47
  • 4
    @Jake That's a good point. One possible solution is to use babel to transpile ES6 into ES5. – Dan Cron Sep 29 '17 at 13:16
  • @HunterMcMillen You can't normally assume everyone is using the latest version of whatever browser - a significant number of web users have a significantly out of date browser. Your use of ES6-specific constructs will break your site for them. – Jake Sep 30 '17 at 01:47
  • 3
    @Jake That is exactly what babel is for. As Dan Cron mentions above. – Hunter McMillen Oct 02 '17 at 15:38
  • 2
    @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. – Keith Mar 21 '18 at 12:58
  • In my case, Dan Cron's tip was fastest to correct my code. As to what Keith says, I definitely agree. As to what @Hunter McMillen said about IE11, I am wondering more generally: Is it reasonable to take into account Microsoft browsers now, since their world market share amounts to peanuts nowadays? Just as Firefox (my favourite one), they are bound to die presently, including Opera. Quoting Keith: ' let's move on'. – Brice C. Apr 02 '22 at 09:32

3 Answers3

2614

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,
}
gen_Eric
  • 214,658
  • 40
  • 293
  • 332
490

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"}
kiranvj
  • 27,729
  • 5
  • 65
  • 72
  • I provided a solution that I think may be of some interest to people at this link using underscore: http://stackoverflow.com/questions/5640988/how-do-i-interpolate-a-variable-as-a-key-in-a-javascript-object/30608422#30608422 – rashadb Jun 02 '15 at 23:46
1

Use this.

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

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

//a:'b'
devtunus
  • 21
  • 1