I've had trouble with people jumping to conclusions about what I need here, so please read this and think about it before answering.
Here is the case:
You have an incoming object. You do not know the structure of this object. You do however have a "target" to something in the object. So let's pretend there is myObject
, and you have some kind of target defined like an array of association levels:
var objectTarget = [ 'firstLevel', 'secondLevel' ,'targetProperty' ];
Now the incoming myObject
looks like this:
{
firstLevel: {
secondLevel: {
targetProperty: "The goods!"
}
}
}
But as stated before, you don't know the structure. All you know is what is in the objectTarget
array.
My problem is being able to address an arbitrary location within an object based solely off a target. If I knew that the target would always be three levels deep, then I could simply reference it like this:
myObject[objectTarget[1]][objectTarget[2]][objectTarget[3]];
However, because I cannot be sure of the number of level depth, this is not adequate. The only way I have been able to accomplish this task is choose a maximum number of reasonable levels, and then switch on it. Like so:
switch ( objectTarget.length) {
case 1:
var result = myObject[objectTarget[1]];
break;
case 2:
var result = myObject[objectTarget[1]][objectTarget[2]];
break;
case 3:
var result = myObject[objectTarget[1]][objectTarget[2]][objectTarget[3]];
break;
case 4:
var result = myObject[objectTarget[1]][objectTarget[2]][objectTarget[3]][objectTarget[1]];
break;
}
..etc
This is obviously extremely messy, and not the optimal solution.
Does this properly explain my problem? Is there a cleaner manner in which to accomplish this?
Thank you in advance for any advice you can provide.