How to access an attribute of an object as a variable?

I have two objects:

object1={ type: 'obj1', nName: 'nName' } object2={ type: 'obj2', pName: 'pName' } 

In my js code, I have:

 object=GET_OBJECT(); 

Method GET_OBJECT() returns either object1, or object2, then I would get access to the name attribute of an object that is either nName or pName.

I have one method that will get the name (pName or nName) of the returned object:

 function getName(Object, name){ return object.name; } 

where I would like name be a variable, so I can access pName or nName as follows:

 object=GET_OBJECT(); var name=''; if(object.type=='obj1') name='nName'; else name='pName'; var finalName=getName(object, name); 

But it does not seem to work with:

 function getName(Object, name){ return object.name; } 

name is a variable. In JS, is there a way to access an attribute as a variable?

+6
source share
2 answers

Try it like this:

 function getName(Object, name) { return Object[name]; } 
+9
source

A.S. many times before I wonder why people provide solutions, not knowledge. Otherwise, the crawler will repeat the same errors again and again.

The source code uses a function to retrieve the attribute. It is assumed that this parameter can be used to invoke the parameter. More technical words use dot notation, which must be a valid JavaScript identifier. The name after the period is a pointer to the contents. Therefore, getName always refers to the attribute name, which is likely to be undefined.

The solution presented uses the Break notation, which uses the parameter value (which may not exist) as an identifier, and then it resolves the content, which is why it really works.

Point labels are faster and easier to read, and they will be recommended if both are valid parameters. The bracket designation should be used when you need to enable at runtime. This is what happens when you define setters and recipients inside. The following code will use the string passed to ensure (using parenthesized notation) that whenever you use the identifier using dot notation, the passed functions are called.

 function myClass(){ //setX and getX should be also defined previous to this this.__defineSetter__("x",this.setX); this.__defineGetter__("x",this.getX); //Object.defineProperty can also be used }; var tObject = new myClass(); tObject.x = 10; //Getter being called 
0
source

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


All Articles