Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript set object key by variable [duplicate]

Tags:

javascript

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/

like image 399
Hunter McMillen Avatar asked Jul 16 '12 16:07

Hunter McMillen


People also ask

Can JavaScript object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

How do you use variables as object keys?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back. Copied!

How do I create a dynamic object key?

To create an object with dynamic keys in JavaScript, you can use ES6's computed property names feature. The computed property names feature allows us to assign an expression as the property name to an object within object literal notation.


1 Answers

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, } 
like image 188
Rocket Hazmat Avatar answered Sep 18 '22 18:09

Rocket Hazmat