How to acess property of object/subobject...

S

surfintheusa

Hi all,

Given the following:

var obj = new Object();
obj.prop1 = 1;
obj.prop2 = 2;
obj.subobj = new Object();
obj.subobj.prop3 = 3;

I'd like to automatically access the right property given it's name
like this:

var propName = whatever; // Can be "prop1", "prop2" or "prop3".
var propValue = obj["" or "subobj"][propName];

Technically, in the case of "prop1" or "prop2" the first square
brackets should disappear. Is there a way to do that?

Thanks!
Terry
 
R

RobG

Hi all,

Given the following:

var obj = new Object();
obj.prop1 = 1;
obj.prop2 = 2;
obj.subobj = new Object();
obj.subobj.prop3 = 3;

I'd like to automatically access the right property given it's name
like this:

var propName = whatever; // Can be "prop1", "prop2" or "prop3".
var propValue = obj["" or "subobj"][propName];

Technically, in the case of "prop1" or "prop2" the first square
brackets should disappear. Is there a way to do that?

Use a function to go down the list of accessors. The following expects
to be passed an object as arg 0, then each accessor in correct order:

function getValue(){
var x = arguments;
var i=0, v = x;
while ( x[++i] ) { v = v[x]; }
return v;
}

// Test based on obj above
var w = 'prop1',
x = 'prop2',
y = 'subobj',
z = 'prop3';

alert(
w + ': ' + getValue(obj, w) + '\n'
+ y + '.' + z + ': ' + getValue(obj, y, z) + '\n'
+ 'obj.' + x + ': ' + obj[x]
);

If the accessors are a single string (say 'subobj.prop3') then use
split('.') to convert it to an array and proceed as above.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top