I am dealing with two distinct objects:
object1={
type: 'obj1',
nName: 'nName'
}
object2={
type: 'obj2',
pName: 'pName'
}
Within my JavaScript code, I have:
object=GET_OBJECT();
The GET_OBJECT()
method will return either object1 or object2. My goal is to access the name attribute of the object, which could be either nName or pName.
I have a method in place to retrieve the name (pName or nName) of the returned object:
function getName(Object, name){
return object.name;
}
I want the name
to be a variable, allowing me to access either pName
or nName
in a flexible manner:
object=GET_OBJECT();
var name='';
if(object.type=='obj1')
name='nName';
else
name='pName';
var finalName=getName(object, name);
Unfortunately, it appears as though this setup may not work as intended, since in:
function getName(Object, name){
return object.name;
}
Is there a way in JavaScript to access an attribute as a variable?