Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript object variable key [duplicate]

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

like image 482
salmane Avatar asked May 20 '11 11:05

salmane


People also ask

Can JavaScript object have duplicate keys?

No, JavaScript objects cannot have duplicate keys. The keys must all be unique.

Can an object key have multiple values JavaScript?

Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

How do you assign a value to an object key?

You need to make the object first, then use [] to set it. var key = "happyCount"; var obj = {}; obj[key] = someValueArray; myArray. push(obj);


1 Answers

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 () {}); 
like image 139
Amadan Avatar answered Sep 18 '22 15:09

Amadan