4

I don't know if this is a logical question, however, I have a weird issue or say a weird requirement. I need to access the value of a dynamically generated variable.

 data:{
 brand: undefined,
 model: undefined
 }
 
 methods:{
 check(){
 let fields = ['brand', 'model'];
 for(let i in fields){
 console.log(`this.${fields[i]}`) // I need this to access the field values
 }
 }
 }
asked Sep 20, 2021 at 12:31
4
  • 1
    @Saniyasyedqureshi it would give me the values in fields array. Thats not what I need. I need to access the data values eg. this.brand and this.model Commented Sep 20, 2021 at 12:35
  • 1
    Just use bracket notation, i.e. this[fields[i]]. Commented Sep 20, 2021 at 12:35
  • 1
    @Terry thanks a lot. Never thought it would be as easy as that. Can you post it as an answer? Commented Sep 20, 2021 at 12:36
  • 1
    Sure thing :) glad that it helped. I can also recommend you use for...of, if it makes things a bit more readable/understandable Commented Sep 20, 2021 at 12:37

1 Answer 1

6

You can just nest the bracket notation, i.e. this[fields[i]]. See proof-of-concept below:

// Suppress annoying console.info
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
 el: '#app',
 data: {
 brand: 'foobar brand',
 model: 'acme model'
 },
 methods: {
 check() {
 let fields = ['brand', 'model'];
 for (const i in fields) {
 console.log(this[fields[i]]);
 }
 }
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"><button type="button" @click="check">Check button</button></div>

Even better: you can use for...of for modern browsers, which avoids the need of a nested bracket notation (improves readability, if it helps):

// Suppress annoying console.info
Vue.config.devtools = false;
Vue.config.productionTip = false;
new Vue({
 el: '#app',
 data: {
 brand: 'foobar brand',
 model: 'acme model'
 },
 methods: {
 check() {
 let fields = ['brand', 'model'];
 for (const field of fields) {
 console.log(this[field]);
 }
 }
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"><button type="button" @click="check">Check button</button></div>

answered Sep 20, 2021 at 12:37
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.