Skip to content Skip to sidebar Skip to footer

Javascript Object Variable Key

I am creating a plugin for Jquery and need to have a variable as a key in an object. $(selector).animate({self.settings.direction: '+='+self.displacement+'px'}, 'slow' , function (

Solution 1:

AFAIK, you can't. Whatever is in front of the colon in the object literal notation will be automatically interpreted as a string. You will need to construct your object beforehand, and use the square bracket notation.

var options = {}
options[self.settings.direction] = '+=' + self.displacement + 'px';
$(selector).animate(options, "slow" , function () {});

Solution 2:

If the value is also a string you could use JSON.parse:

var a = 'key';
var b = 'value';
var test = JSON.parse('{"' + a + '":"' + b + '"}"');
//test = {key: 'value'}

Solution 3:

You can access the string defined by a variable with toString(). so :

var obj = newObject;

obj.a = 0;
obj.b = 1;

var a = "b";

obj["a"]; // will output 0
obj[a.toString()] // will output 1

Solution 4:

Keep in mind you are defining an object there between the curly brackets. You can't use dots in property names. Assuming the displacement property is set somewhere else earlier, this will work for you:

$(selector).animate({settings: {direction: '+='+self.displacement+'px'}}, "slow" , function () {})

Post a Comment for "Javascript Object Variable Key"