Skip to content Skip to sidebar Skip to footer

Passing A String From Variable As A Key In Javascript Object Literal

How can i do this? objPrefix = btn.attr('data-objprefix'); //

Solution 1:

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')

Post a Comment for "Passing A String From Variable As A Key In Javascript Object Literal"