Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign variable value as variable name in a hash?

Tags:

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?

like image 285
mikkelbreum Avatar asked Nov 16 '10 21:11

mikkelbreum


People also ask

Is hash a valid variable name?

If you mean #, it's invalid to use as part of a variable name because it's a punctuation mark. You wouldn't use a ',' either. It's not a mixed meaning thing like a '.

What is hash variable?

Definition. Hash Variables gives users greater flexibility and freedom in accessing useful information or relevant run-time values from the system. A hash variable is a special hash-escaped keyword that can be used in : Form Builder. Datalist Builder.


2 Answers

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.

like image 195
Daniel Vandersluis Avatar answered Sep 22 '22 00:09

Daniel Vandersluis


var setname = 'set_1', 
    elements = {};

elements[setname] = ['beer','water','wine'];
like image 44
kanaka Avatar answered Sep 20 '22 00:09

kanaka