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
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
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);
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.
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.