Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access attribute of 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();

The GET_OBJECT() method returns either object1 or object2, then, I would like to access the object's name attribute which is either nName or pName.

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

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

where I would like the name to be a variable, so that I can access the pName or nName in this way:

object=GET_OBJECT();

var name='';

if(object.type=='obj1')
   name='nName';
else
   name='pName';

var finalName=getName(object, name);

But seems it won't work since in:

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

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

like image 227
Mellon Avatar asked Apr 26 '11 08:04

Mellon


People also ask

How do you access the properties of an object with a variable?

Answer: Use the Square Bracket ( [] ) Notation There are two ways to access or get the value of a property from an object — the dot ( . ) notation, like obj. foo , and the square bracket ( [] ) notation, like obj[foo] .

How do you access object properties dynamically?

To access the object property dynamically in JS, you need to pass the property name as a string in square brackets. As the value of the variable key changed, we got access to the different properties of the user object. The most common way to access the object properties in JavaScript is the dot.

How do you use object variables?

You should declare the object variable with the specific class that you intend to assign to it ( Control in this case). Once you assign an object to the variable, you can treat it exactly the same as you treat the object to which it refers. You can set or retrieve the properties of the object or use any of its methods.

Can object key be a variable?

JavaScript object key names must adhere to some restrictions to be valid. Key names must either be strings or valid identifier or variable names (i.e. special characters such as - are not allowed in key names that are not strings).


1 Answers

Try like this:

function getName(Object, name) {
    return Object[name];
}
like image 63
Darin Dimitrov Avatar answered Sep 22 '22 00:09

Darin Dimitrov