6
//Admin.js

var insertAdminFeed = function(s, id, timestamp){
    var admin_att_new_key = '12345';
    var admin_att_new_key2 = 'abc';
    var admin_att_new_key3 = 'zyzyz';

    var s = 'admin_att_new_key';
    console.log(global[s]); //should print '12345'
};
exports.insertAdminFeed = insertAdminFeed;

I want to convert a string to a variable in node.js (I have many keys, and I don't want to write if/else statements for all of them) How can I do that?

3
  • Why don't you use objects instead? Commented Jan 9, 2014 at 0:32
  • You can't. This will be possible in ES6 (with symbols) very nicely but in ES5 unless you use a parser you have no way to access a variable's name from itself. You also can not iterate over all closure variables. What you should do is probably var admin= {key:'12345',key2:'abc',key3:'zyzyzy'} and then use Object.keys(admin) to iterate through those keys when you need them. Commented Jan 9, 2014 at 0:34
  • 4
    Node.js modules aren't run in the global scope like JavaScript in a browser, vars also scope to functions, and admin_att_new_key{,2,3} seems rather like the start of an Array. Commented Jan 9, 2014 at 0:34

1 Answer 1

10

This is not really possible in JavaScript.

You'd usually use an object literal to achieve similar needs.

var key = 'foo';
obj[key] = 1;
obj['foo'];

To be thorough, it is technically possible in JS using eval. But really, don't do this.

eval("var "+ name + " = 'some value';");
eval("console.log("+ name  +")");
Sign up to request clarification or add additional context in comments.

1 Comment

I agree that its a bad idea, but eval(s) (assuming s defined as in the question) would work - no need for the variable to also be declared in an eval.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.