简体   繁体   中英

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

I'm trying to get a variable from an object, but the variable key is coming from another variable's value.

Here's what I'm trying to explain:

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;
    }

Instead of all this I just want to do:

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

When category is actually a var with a key of category, so category's value should be "personal" for instance, and then it will access the personal item inside the object.

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

Property accessors provide access to an object's properties by using the dot notation:

obj.prop

or the bracket notation:

obj[propStr]

Therefore you can change the code to:

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

Read here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM