javascript - Evaluate string as Object without eval() dynamically? -


Edit: thank you and everyone else who responds like this was really one ... then I Do not miss it stupid.

Maybe the answer is so simple that it is getting rid of me ... but I know that someone with this hope can give me the school.

So I have got a huge project which is working with huge JSON, objects, arrays etc. and I dynamically access this data without prior knowledge of the actual data. Required of them I know something [string] works, but I need [string] [string] [string], etc. In other words, the whole thing should be completely dynamic.

I know, I know, there are performance problems with this approach and I am sure that there are better ways, but I am the successor of this problem and I believe it is not an option to change it. is. Now, here is a super recoil on simple examples. To prove the underlying problem, I can not find a way without using eval (), which I can not use because the data is not coming to reliable sources.

In this example, show that foo and bar (both object names and corresponding option values) are not able to determine the runtime. Let's say that for simplicity they are printing w / your favorite server-side code.

  & lt; Script & gt; // The pretending of these objects / dOM is dynamically inserted from somewhere // so long as we run the runtime var foo = {value: "something"} var bar = {value: "something else"} window Do not know .onload = function () {function alertValue (option) {// vvvv} This is what I can do var selected_object = eval (option.getAttribute ("value")); Var selected_value = selected_object.value; Warning (selected_value); } Var option1 = document.getElementById ("option1"); Var option 2 = document. GetElementById ("option2"); Option1.onclick = function () {alertValue (this); } Option2.onclick = function () {alertValue (this); }} & Lt; / Script & gt; & Lt; Html & gt; & Lt; Gt selection and; & Lt ;! - These values ​​are generated on runtime server side - & gt; & Lt; Option id = "option1" value = "foo" & gt; The value of Fu & lt; / Option & gt; & Lt; Option id = "option 2" value = "bar" & gt; Value of bar & lt; / Options & gt; & Lt; / Select & gt; & Lt; / Html & gt;  

Any help would be great, I hope this is a simple "DOH" moment. Please do not separate this code or there is no reason for the method. This is not complicated anywhere as a real project. This is the only proof of concept, so you get the problem.

If you are executing it in a browser, the global context is the window Can be referred to, therefore

  var selected_bizet = window [option.getAttribute ("value")];  

(Or I could not understand what your problem is.)


Comments