0

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.

Greeso
  • 7,544
  • 9
  • 51
  • 77
  • You can use a simple helper function that splits the string and handles as many levels of nesting as required before returning the value of the required property. See the linked duplicate, or [this question](https://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference) amongst [others](https://stackoverflow.com/questions/8817394/javascript-get-deep-value-from-object-by-passing-path-to-it-as-string). – nnnnnn Aug 30 '17 at 03:48
  • @nnnnnn - Thanks man. I will check the other question. – Greeso Aug 30 '17 at 03:59
  • https://gist.github.com/Ricardinh0/8e5424073a2f1aad606d5deb54a19102 – Ricardinho Aug 30 '17 at 04:09

0 Answers0