Javascript notation with variable

I don’t know how to say it.

I am trying to use a variable to determine how far to drill an object to return a value.

var target = "level1.level2.var"; var myObject = { level1: { level2: { var: 'value' } } } var returnVal = myObject.target; 

How can I do that? Clearly this will not work. Is this possible in another way?

I decided that I might have to blow up the target var, and then the loop for each level, but thought I'd ask to see if there was any simpler way I could forget.

+4
source share
5 answers

You can use this function:

 function get_property_from_target(obj, target){ var arr = target.split('.'); for(var i = 0; i < arr.length; i++){ if(obj) obj = obj[arr[i]]; } return obj; } 

Then name it like this:

 get_property_from_target(myObject, target); 

I would rename the function to something better.

Also, do not name the property of var objects, since this is a keyword in Javascript, this can be confusing, and I'm not sure if it will always work the way you expect, or if it just causes errors in some browsers.

+9
source

Easier? Of course use eval :

 var obj = eval('myObject.' + target); 

This is not a very serious answer. You should not use eval this way in good code. The only other way, as far as I know, is the loop that you describe:

 var items = target.split('.'); var obj = myObject; var i; for(i = 0; i < items.length; i++) { obj = obj[items[i]]; } 

Or with hack regex:

 var obj = myObject; target.replace(/[^\.]+/g, function(m) { obj = obj[m]; }); 

Regardless, you can use obj .

+4
source

I see two ways to do this:

  • Using eval() (frowning as eval is evil ):

     var returnVal = eval('myObject.' + target); 
  • Using a loop:

     var split = target.split('.'); var newTarget = myObject; for (var i = 0; i < split.length; i++) { newTarget = newTarget[split[i]]; } 
+2
source

there is no way other than writing code to divide your goal into . , then for each token, expand the object until the "path" is valid.

+1
source

What I would do (maybe not the best, but it will work) is what you suggested. Expand the variable, and then go to that level.

 var target = "level1.level2.var"; target = target.split('.'); var returnVal = myObject; for(var i=0,len=target.length; i<len; i++){ returnVal = returnVal[target[i]]; } console.log(returnVal); // value 
+1
source

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


All Articles