tags:

views:

67

answers:

2

Let me try to explain this, I have a string like this:

"b.c"

And an object like this:

a = {
    b:{
        c:2
    }
}

I would like to use that string to get the c property, but using this doesn't work:

a["b.c"]

How can I use the "b.c" string to work just like a.b.c? (Without using eval, perfomance is important in my case)

+6  A: 

What about something like this:

function load(path) {
    var steps = path.split('.');
    var level = this;
    for(var i=0;i<steps.length;i++) {
        level = level[steps[i]];
    }
    return level;
};

var value = load(a, 'b.c');
Rex M
Thanks for the fast reply! I'll accept your questions when SO allows me to.
M28
Augmenting the `Object.prototype` object is *not* really a good idea, almost all objects (including host objects such as DOM elements) inherit from it, for example if you use the `for-in` statement on an object, the inherited `load` property will be enumerated, e.g.: `for (var p in {}) alert(p);`. It also can cause problems with other libraries, check [this example](http://jsbin.com/awalu3/2/edit) with jQuery and your function. Why not a simple function like `function load(obj, path) {` ?
CMS
Elegant solution, also good point from CMS. +1 both.
karim79
@CMS true. I don't often use `for-in` so naively that an extra function appearing in the enumeration would be an unhandled surprise... do you?
Rex M
@Rex, yes, a really common problem with people not familiar with the language is the usage of the `for-in` statement to *"iterate"* over Array or Array-like objects -it looks similar to e.g. `foreach` in other languages (C#, php, etc)- and this will really cause a problem. Also as you can see that simple addition to the `Object.prototype` broke jQuery hehe.
CMS
+3  A: 

Another approach using the Array.prototype.reduce method:

function load(obj, path) {
  return path.split('.').reduce(function (a, b) {
    return a[b];
  }, obj);
}

Usage:

var a = {
  b: {
    c: 2
  }
};


load(a, 'b.c'); // 2

Notes:

1- The reduce method is not available on IE <= 8, but a standard compliant version can be found in the liked page.

2- You should keep in mind that property names can contain dots, e.g.:

var a = {
  "foo.bar": 10
};

If this cause you problems, it would be better to pass an array to the function, containing the property names to the function, instead of a dot-separated string.

CMS