How to Use a Variable For a Key in a JavaScript Object Literal

How to use a variable for a key in a JavaScript object literal?

{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:

obj = { thetop : 10 };
obj = { "thetop" : 10 };

In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:

var thetop = "top";

// create the object literal
var aniArgs = {};

// Assign the variable property name with a value of 10
aniArgs[thetop] = 10;

// Pass the resulting object to the animate method
<something>.stop().animate(
aniArgs, 10
);

ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:

var thetop = "top",
obj = { [thetop]: 10 };

console.log(obj.top); // -> 10

You can use this new syntax in the latest versions of each mainstream browser.

dynamic keys for object literals in Javascript

You can set dynamic keys is with bracket notation:

required.directories[this.applicationPath + "/configs"] = "Application config folder does not exists";

(of course wherever you do this definition, this.applicationPath must exist)

But do you need this.applicationPath in the keys? How do you access theses values? Maybe you can just remove this.applicationPath from whatever value you use to access the properties.


But in case you need it:

You could use an array to initialize the keys if you want to avoid repeating a lot of code:

var dirs = ['configs', 'controllers', ...];
var files = ['init.js', 'controllers/index.js', ...];

var required = { directories: {}, files: {} };
required.directories[this.applicationPath] = "Application " + this.application + " does not exists";

for(var i = dirs.length; i--;) {
required.directories[this.applicationPath + '/' + dirs[i]] = "Application " + dirs[i] + " folder does not exists";
}

for(var i = files.length; i--;) {
// same here
}

JavaScript set object key by variable

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

Behavior of Javascript object literals (using a variable as a key value)

That's simply Javascript syntax... When initializing an object the key names are taken literally even if there is a variable of the same name.

If you'd like to keep that syntax you may be interested in computed property names (see "New notations in ECMAScript 2015" of the article linked above).

return {...obj, [name]: value} 

I think it's worth pointing out that this syntax creates a new object which copies the key/value pairs from the old object. That may or may not be important if your program relies on obj being == or === to a stored variable.

If you want to keep the same object and simply add a new property, you can always just add it on.

obj[name] = value;
return obj;

Is there a way to use variable keys in a JavaScript object literal?

In ES6, use computed property names.

const key = "anything";   

const object = {
[key]: "key attribute"
// ^^^^^ COMPUTED PROPERTY NAME
};

Note the square brackets around key. You can actually specify any expression in the square brackets, not just a variable.

Passing a string from variable as a key in javascript object literal

When you use the literal notation objPrefix is considered as the keyname itself and not value of the variable objPrefix, Instead try use bracket notation to set the property name for the object based on a variable value. So try this way:

var sendData = {};
sendData[objPrefix] = {"bar":"ccccc"};

Also you can infact use jquery data-api to fetch the value of data-attribute i.e

objPrefix  = btn.data('objprefix')

Use a variable as the key in an object literal (to pass to jQuery's animate)?

That's because you can't use a variable as the key in an object literal. A solution to achieve that is creating an empty object, then using bracket notation to name a new key from a variable:

var animationAttribute = 'left';
var newTarget = 500;
var animationParams = {};
animationParams[animationAttribute] = newTarget;

$(element[0].selector).stop().animate(animationParams, 400, 'linear');

How to use template literal as key inside object literal?

And of course I come up with a solution straight away:

{
[`${id}_name`]: "John Doe",
[`${id}_age`]: 27,
}

Wrap the template literal in square brackets. This will evaluate the expression in between the square brackets and use it as the key.

Without square brackets, only identifiers (e.g. my_key_name), single or double quote strings (e.g. "My Key Name") and numbers (e.g. 42) can be used.

How do I make a variable in the updated object for my setter function?

Use [positionKey] instead of a fixed value

onClick={() => setTeam({ ...team, [positionKey]: null })}

see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names



Related Topics



Leave a reply



Submit