su**********@yahoo.com wrote:
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[i];
while ( x[++i] ) { v = v[x[i]]; }
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.
--
Rob