在JavaScript我怎么能动态获取对象的嵌套属性

在JavaScript我怎么能动态获取对象的嵌套属性

问题描述:

var arr = { foo : 1, bar: { baz : 2 }, bee : 3 }

function getter(variable) {
  return arr[variable];
}

如果我想'富'VS'蜜蜂'我可以做改编[可变] - 这很容易,而且功能确实是

If I want 'foo' vs 'bee' I can just do arr[variable] - that's easy, and the function does that.

但是,如果我想获得 arr.bar.baz AKA 改编什么[巴] [巴兹]

But what if I want to get arr.bar.baz AKA arr[bar][baz]?

我可以通过吸气剂的功能,可以让我做那是什么,(当然也让我使用相同的函数来获取非嵌套的属性)。

What can I pass to the getter function that will let me do that, (and of course also let me get non-nested properties using the same function).

我试过吸气剂('bar.baz')吸气剂('[巴] [巴兹]')但那些没有工作。

I tried getter('bar.baz') and getter('[bar][baz]') but those didn't work.

我想我可以解析为点或括号(喜欢这里:In JavaScript中,测试性能深深嵌套在对象图?)。是否有一个更清洁的方式? (当然除了EVAL)。

I suppose I can parse for dots or brackets (like here: In javascript, test for property deeply nested in object graph?). Is there a cleaner way? (Besides eval of course.)

尤其是因为我需要在一个循环中深深设置正确很多很多次了一堆数组中的元素。

Especially because I need to get the deeply set properly many many times in a loop for a bunch of array elements.

如何变化的getter函数签名吸气剂('巴','巴兹')而不是

How about change the getter function signature as getter('bar', 'baz') instead

function getter() {
  var v = arr;
  for(var i=0; i< arguments.length; i++) {
    if(!v) return null;
    v = v[arguments[i]];
  }
  return v;
}

PS。没有测试,但你的想法;)

ps. didn't test, but you get the idea ;)