In Javascript, how do I convert a string so that it can be used to call a property?

So, I have an associative array, and the keys in the array are the properties of the object. I want the loop through the array and in each intervention do something like this:

Object.key 

This, however, does not work and results in an undefined return, not a property value.

Is there any way to do this?

+4
source share
3 answers

You can use the for ... in loop:

 for (var key in obj) { //key is a string containing the property name. if (!obj.hasOwnProperty(key)) continue; //Skip properties inherited from the prototype var value = obj[key]; } 
+10
source

You must use accessory notation properties:>

 var value = object[key]; 

This operator can even evaluate expressions, for example:

 var value = object[condition ? 'key1' : 'key2']; 

Additional Information:

Remember that Array object methods that expect to work with numeric indexes can add any property name, but this is not recommended instead, instead of intensifying the Array object (i.e. var obj = []; or var obj = new Array(); ), you can use a simple instance of the object (i.e. var obj = {} or var obj = new Object();

+9
source

Yes. Assuming key is a string, try myObject[key]

+2
source

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


All Articles