Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a string to a variable name in Node.js? [duplicate]

//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?

like image 926
TIMEX Avatar asked Dec 26 '22 15:12

TIMEX


1 Answers

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  +")");
like image 180
Simon Boudrias Avatar answered Dec 28 '22 07:12

Simon Boudrias