将变量动态插入 JavaScript 和 Angular 中的对象路径

Dynamically insert variable into object path in JavaScript and Angular

我不知道我是否理解错了这个概念,但是搜索了几个小时没有得到任何结果。

我想根据用户从下拉列表中选择的 'type' 为表单动态加载字段。这通过 angular 绑定到变量 "currentType"。那部分有效。

currentType = //whatever the user chose. Will evaluate to either "category1" or "category2"
currentFields = {}
fields = {
           'category1': {
                          propertyInfo {
                                        'label1'
                                        'label2'
                                        'label3'
                                        'label4'
           'category2': {
                          propertyInfo {
                                        'label5'
                                        'label6'
                                        'label7'
                                        'label8'

我想发生的事情是选择类型时,将加载字段。所以:

currentFields = field."currentType".propertyInfo

我不知道如何将该变量插入到对象路径中。我不断收到有关字段没有 属性 "currentType".

的错误

应该这么简单(感谢JS的动态特性):

currentFields = field[currentType].propertyInfo

如果你不知道,它是这样工作的。如果你有对象:

var foo = {
  bar: "42"
}

"42" 可作为 foo.barfoo['bar'].

访问