0

I have read quite often how to call a function using a string in JavaScript. But how can I get the property of an object on the same way? This post demonstrates how to use strings in order to call functions. How can I realize the same thing with object properties?

I tried this: Fiddle

But this line does not give me the desired result.

alert( window[val] ); 

What am I doing wrong ?

That´s the full code:

f1("obj.key"); 

function f1(val){
   var obj={
      key : "Hello World"
   };
   alert( obj.key );       // Hello World
   alert( window[val] );   // undefined
}
Community
  • 1
  • 1
wurstbrotrest
  • 329
  • 1
  • 7
  • 17
  • 1
    Why would it work? You've never defined such properties to the `window`. – Teemu Mar 29 '15 at 17:13
  • Would `window.obj.key` resolve to anything? Is function belonging to the window? – clearlight Mar 29 '15 at 17:14
  • 1
    possible duplicate of [Accessing nested JavaScript objects with string key](http://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – Andreas Mar 29 '15 at 17:14

2 Answers2

0

first, obj is defined only inside the function scope, if you want window to know it, you should create it on the global scope (outside the function scope). second, you should call window["obj"]["key"] (separate the strings from the sides of the dot). good luck!

MoranF
  • 21
  • 3
0

Theres two issues that this had. First is because you are declaring var before obj, you are setting the scope to the function so it wont be accessible to the window. Secondly, whatever you put in the brackets of window[val] has to be a direct attribute of the window object. Essentially you will need to pass in window[obj][key].

Essentially for what you are doing you would use something like this:

f1("obj.key"); 

function f1(val){
   obj={
      key : "Hello World"
   };

   var current = window;
   var attributes = val.split( '.' );
   for (var i = 0; i < attributes.length; i++) {
            current = current[attributes[i]];
   }

   $('#2').text( obj.key );     // works fine
   $('#1').text( current ); // Based on the string you pass
}`