JS / ANGULAR 使用 var 的值作为另一个对象的键

JS / ANGULAR Use a var's value as the key for another object

我正在尝试从对象中获取变量,但变量键来自另一个变量的值。

以下是我要解释的内容:

vm.getQuestion = function(category) {
        switch (category) {
          case "personal":
            var query = vm.queryBank.personal[vm.currentQueryNum];
            break;
          case "taste":
            var query = vm.queryBank.taste[vm.currentQueryNum];
            break;
          case "skills":
            var query = vm.queryBank.skills[vm.currentQueryNum];
            break;
          case "habits":
            var query = vm.queryBank.habits[vm.currentQueryNum];
            break;
          case "feedback":
            var query = vm.queryBank.feedback[vm.currentQueryNum];
            break;
          case "usabilty":
            var query = vm.queryBank.usabilty[vm.currentQueryNum];
            break;
          case "hobbies":
            var query = vm.queryBank.hobbies[vm.currentQueryNum];
            break;
          case "custom":
            alert('Not yet baba!');
            break;
          default:
            console.log('category not valid: '+category);
        }
        vm.currentQuery = query;
    }

我只想做的不是这些:

vm.currentQuery = vm.queryBank.category[vm.currentQueryNum];

category实际上是一个以category为键的var,所以category的值应该是"personal",然后它会访问对象内部的个人项目。

if ( typeof vm.queryBank[ category ] === 'undefined' ) {
  throw 'Unsupported category "' + category + '".';
}
vm.currentQuery = vm.queryBank[ category ][ vm.currentQueryNum ];

属性 访问器使用点表示法提供对对象属性的访问:

obj.prop

或括号表示法:

obj[propStr]

因此您可以将代码更改为:

vm.currentQuery = vm.queryBank[category][vm.currentQueryNum];

阅读here