Coder Perfect

The object key is set using a variable in JavaScript. [duplicate]


I’m making some JavaScript objects and pushing them into an array. I’m storing the key I want to utilize in a variable and then creating my objects as follows:

var key = "happyCount";
myArray.push( { key : someValueArray } );

However, when I try to go through my array of objects, the key is “key” rather than the value of the variable key. Is it possible to set the key’s value from a variable? for a more detailed explanation:

Asked by Hunter McMillen

Solution #1

You must first create the object before using [] to set it.

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

obj[key] = someValueArray;

UPDATE 2021:

In ECMAScript 2015 (ES6), the computed property names feature was introduced, which allows you to dynamically generate the names of object properties in JavaScript object literal notation.

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

const obj = {
    [yourKeyVariable]: someValueArray,

Answered by Rocket Hazmat

Solution #2

You can do something similar in ES6.

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

It’s known as Computed Property Names, and it’s written in bracket notation (square brackets) [].

For instance, [variableName]: someValue

Try something like this for ES5.

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );


var person = {};
var key = "name";

person[key] /* this is same as */ = "John";

console.log(person); // should print  Object { name="John"}

Answered by kiranvj

Post is based on