tags:

views:

1905

answers:

3

hello everyone,

I am new to stackoverflow but I found it pretty helpful several times. Now I have my own question: Is there a way to convert variable names to strings in javascript? To be more specific:

var a = 1, b = 2, c = 'hello';
var array = [a, b, c];

Now at some point as I go through the array, I need to get variable names (instead of their values) as strings - that would be 'a' or 'b' or 'c'. And I really need it to be a string so it is writeable. How can I do that?

Thank you

jirkap

+7  A: 

Use a Javascript object literal:

var obj = {
    'a': 1,
    'b': 2,
    'c': 'hello'
};

You can then traverse it like this:

for (name in obj){
    alert(name);
    alert(obj[name]);
}

And access properties on the object like this:

alert(obj.a);
alert(obj.c);
Triptych
The quotes around the properties' names are optional - why not save yourself some typing and drop them?
Christoph
Actually, I am glad he included the quotes, it all together makes much more sense to me.
jirkap
There are several ways to populate an object literal with values - choose the one you like best: obj={a:5}; obj={'a':5}; obj={},obj.a=5; obj={},obj['a']=5;
Christoph
I originally didn't have quotes - check my edits. Decided to add them because, in some cases, you do need quotes. And JSON requires quotes. It's just a good habit to pick up.
Triptych
Good example. (But don't encourage so many alert()s!!!!!)
Jason S
I would normally do console.log() of course, but I didn't want to assume Firebug.
Triptych
+1  A: 

What you could do is something like:

var hash = {};
hash.a = 1;
hash.b = 2;
hash.c = 'hello';
for(key in hash) {
    // key would be 'a' and hash[key] would be 1, and so on.
}
Paolo Bergantino
A: 

Thank you both. It works.

jirkap