28

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 () {});

this part causes the error:

self.settings.direction

any ideas where my syntax is wrong? thank you

salmane
  • 4,799
  • 13
  • 48
  • 61
  • I think the following link shows a pretty good solution I came up with for this using underscore. It couldn't be easier! 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:47

4 Answers4

85

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 () {});

EDIT: You can now:

const prop = "foo"
const bad = { prop: "bar" } // { prop: "bar" }
const good = { [prop]: "bar" } // { foo: "bar" }

so...

$(selector).animate({ [self.settings.direction]: '+='+self.displacement+'px'}, "slow" , function () {});
Amadan
  • 191,408
  • 23
  • 240
  • 301
11

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'}
Ronald
  • 383
  • 3
  • 8
7

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

var obj = new Object;

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

var a = "b";

obj["a"]; // will output 0
obj[a.toString()] // will output 1
seth.miller
  • 1,988
  • 17
  • 23
Mathieu
  • 79
  • 1
  • 1
  • 6
    The `.toString()` call is unnecessary. The variable `a` is already a string. All you need to do is remove the quotes: http://jsfiddle.net/FJCFW/. – Travesty3 Jan 18 '13 at 13:42
1

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 () {})
rciq
  • 1,309
  • 10
  • 10