I have a a JavaScript object defined as follows
function MyObject () {
this.x = 10;
this.foo = {
x: 20
};
this.bar = {
baz: {
x: 30
}
}
}
And I am using the above object as follows:
var n = new MyObject();
At some point in my code, I need to refer to the properties of the above object via strings. Here is an example
var s1 = 'x';
var result1 = n[s1]; // Works. result1 = 10.
var s2 = 'foo.x';
var result2 = n[s2] // Does not work, result2 = undefined. Was hoping result2 = 20.
var s3 = 'bar.baz.x';
var result3 = n[s3] // Does not work, result 3 = undefined. Was hoping result3 = 30.
As you can see in the above example, result2
and result3
would be undefined
, and this is what I expected but not what I wished would happen. I need a way to convert the strings s2
and s3
into the following
var result2 = n['foo']['x'];
var result3 = n['bar']['baz']['x'];
Note that I am splitting the s2
and s3
strings into the array variables.
One approach was to do the following
var s2 = 'foo.x';
var s2Array = s2.split('.');
var result2 = n[s2Array[0]][s2Array[1]];
But I do not think this approach is very feasible, because I am not sure how deep the string variables will be (e.g., foo.x
or bar.baz.x
), and also I would like a generic solution that would work on any level (e.g, the solution should also work qux.quux.quuz.corge.grault.garply.waldo.x
).
Thanks.