-4

Is there any way to take a JavaScript string such as

"program[one] = js"

and run on this string and make it accessible so that when I type

console.log(program.one); 

I will get js

mega6382
  • 9,211
  • 17
  • 48
  • 69
Mumfordwiz
  • 1,483
  • 4
  • 19
  • 31

3 Answers3

0

You can use the eval method (although it is not highly recommanded) and do something like this:

var program = {};

var str = "program['one'] = 'js'";

eval(str);

console.log(program.one);
Shai Aharoni
  • 1,955
  • 13
  • 25
0

Assuming that you only want to allow the string to write in program and that the only valid strings are of the form program[name] = value there is a not evil solution:

var program = {};

var input = "program[one] = js";

var patt = /program\[(.*?)\] = (.*)/;
var result = patt.exec(input); // Array [ "program[one] = js", "one", "js" ]

program[result[1]] = result[2];

console.log(program.one); // js

Edit: you may have to tweak the regular expression (patt) if you need to support quotes, and ending semicolon.


Using eval is considered harmful. If you are not in control of the string passed to it - which often is the case - it could run any code allowing for code injection. No, do not pretend you can do what I did above for arbitrary programs. On the other hand, if you are in control of the string, you shouldn't need eval - although I accept it may be practical if you are using metaprogramming by code generation in javascript.

Community
  • 1
  • 1
Theraot
  • 31,890
  • 5
  • 57
  • 86
0

You're thinking about this backwards.

What you want is some JSON that represents a JS object that you can parse.

var json = '{"program":{"one": "js"}}';
var obj = JSON.parse(json);

obj.program.one // js

Even if you're not thinking about this backwards you do need to go back and work out why you need to use a string like "program[one] = js" because the approach is wrong-headed and will only lead to heartache.

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95