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?
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] .
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.
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.
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).
Try like this:
function getName(Object, name) {
return Object[name];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With