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

1
  • I think the following link shows a pretty good solution I came up with for this using underscore. It couldn't be easier! stackoverflow.com/questions/5640988/… Commented Jun 2, 2015 at 23:47

4 Answers 4

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 () {});
Sign up to request clarification or add additional context in comments.

1 Comment

Easy to forget that's available
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'}

3 Comments

+1: equal parts ugly and useful. Very handy.
What is this dark magic!? They should include this method in Coffeescript to add variable key superpowers.
might be a good idea to escape double quotes like: JSON.parse('{\"' + a + '\":\"' + b + '\"}')
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

1 Comment

The .toString() call is unnecessary. The variable a is already a string. All you need to do is remove the quotes: jsfiddle.net/FJCFW.
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 () {})

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.