开发者

Using . in a [] to enter in a new scope

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 us开发者_如何学运维e 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)


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');


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜