Compute a string as an object without eval () dynamically?

EDIT: Thanks to Kenny and everyone who answered in a similar way. It really was a DOH ... So stupid that I don't remember that.

Maybe the answer is so simple that it eludes me ... but I know that someone here can visit me on this, I hope.

So, I have a rather large project that concerns a ton of very large JSON, objects, arrays, etc. And I need a way to dynamically access this data without first knowing the actual names. I know that someobjectname [string] works, but I need [string] [string] [string] etc. In other words, the whole thing must be fully dynamic.

I know, I know that there are performance issues with this approach, and I'm sure there are better methods, but I inherit this problem and believe that this is not an option to change it.

NOW, here is a super-suber according to a simplified example, to prove the main problem. I cannot find a way without using eval (), which I cannot use, because the data is NOT reliable sources.

In this example, pretend that foo and bar (both the names of the objects and the corresponding parameter values) CANNOT know before runtime. Say for simplicity they are printed with your favorite server code.

<script>
// Pretend these objects are inserted into
// the DOM dynamically from where ever
// so we don't know the names till runtime
var foo = {
   value : "something"
}

var bar = {
   value : "something else"
}

window.onload = function() {

    function alertValue(option) {
                            // vvvv This is what I can't do
         var selected_object = eval(option.getAttribute("value"));
         var selected_value = selected_object.value;
         alert(selected_value);    
    }

    var option1 = document.getElementById("option1"); 
    var option2 = document.getElementById("option2");  

    option1.onclick = function () {
         alertValue(this);
    }

    option2.onclick = function () {
        alertValue(this);
    }

}

</script>

<html>
    <select>   <!-- Pretend these values are generated at runtime serverside -->
        <option id="option1" value="foo">Foo value</option>
        <option id="option2" value="bar">Bar value</option>
    </select>
</html>

. , "DOH". , , . , . , .

+3
3

, window,

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

( , .)

+3

, , , foo bar window["foo"] window["bar"].

+3

foo.bar foo["bar"] Javascript. , . ; foo["bar"]["baz"] , foo.bar.baz.

+2
source

Source: https://habr.com/ru/post/1755273/


All Articles