Reputation: 3081
I need to define a hash for posting some ajax data using jQuery. The hash will look something like:
var setname = 'set_1';
elements = { set_1: {'beer','water','wine'} };
The challenge I need to solve is 'set-1' (the key of Array elements) should be dynamically named based on the value of var setname
.
I want to avoid using eval()
of course..
in PHP it can be done using the double dollar sign like this: $$setname
, but what's the way to do this in JavaScript?
Upvotes: 22
Views: 29605
Reputation: 23537
Directly use the identifier in square brackets:
const setname = 'set_1';
const elements = { [setname]: ['beer','water','wine'] }
Please bear in mind the usage of square brackets for lists
Upvotes: 2
Reputation: 413818
You have to understand that there's really no such thing as "JSON notation" in Javascript - it's native Javascript notation that we're talking about. What jQuery wants is a Javascript value for the POST data, not necessarily a Javascript object constant.
Thus, your code will prepare your POST data like this:
var elements = {};
elements[setName] = { /* something */ };
elements[somethingElse] = { /* something else */ };
and so on. When you're ready to do the POST, you'd just use "elements":
$.post(url, elements, function() { /* callback code */ });
Upvotes: 3
Reputation: 94253
You can do what you'd like to like so:
var setname = 'set_1', elements = {};
elements[setname] = ['beer','water','wine'];
alert(elements['set_1']); // beer,water,wine
See this in action at http://jsfiddle.net/x5KRD/.
All objects in JS can be accessed using dot notation (obj.method()
or obj.property
), or bracket notation (obj['method']()
or obj['property']
). Using bracket notation lets you dynamically specify method/property/key names.
For example, while clumsy, window['alert']('hi')
is equivalent to window.alert('hi')
.
Note that your code won't work as-is, anyways, because you're using object literal notation ({'beer','water','wine'}
) to contain an array (it should be in square brackets ['beer','water','wine']
instead). Object literals need to have key-value pairs.
Upvotes: 35
Reputation: 73187
var setname = 'set_1',
elements = {};
elements[setname] = ['beer','water','wine'];
Upvotes: 6