0

I have code something like this.

  new Vue({
  el:'#app',
  data:{
    cars:[
      {
        name:'',
        make:''
      }
    ]
  },
  methods:{
    addToArray(nameOfTheArray){ //here nameOfTheArray is the string "cars"
      //so here I have to do something like this
      this.cars.push({
         name:'',
        make:''
      })
 }
  }
})

My question is can I use that argument(nameOfTheArray) to tell in which array I want to push this object. I mean something like this?

 this.nameOfTheArray.push({
         name:'',
        make:''
      })

but this doesn't work. is there any way to use that string argument with this keyword??

2
  • Yest, just use it like an array. this[nameOfTheArray].push Commented Mar 16, 2018 at 20:50
  • also, you method should be addToArray: function(nameOfTheArray){ Commented Mar 16, 2018 at 20:52

2 Answers 2

1

use this :

  new Vue({
  el:'#app',
  data:{
    cars:[
      {
        name:'',
        make:''
      }
    ]
  },
  methods:{
    addToArray(nameOfTheArray){ 
      this[nameOfTheArray].push({
         name:'',
         make:''
      })
 }
  }
})
Sign up to request clarification or add additional context in comments.

Comments

1

You can access to an object property by obj[key], also check if the key exists in the object to avoid runtime errors

 new Vue({
  el:'#example',
  data:{
    cars:[
      {
        name:'',
        make:''
      }
    ]
  },
  methods:{
    addToArray(nameOfTheArray){
      if (nameOfTheArray in this) {
        this[nameOfTheArray].push({
         name: 'default name',
         make: 'default make'
        })
      } else {
        alert('Invalid key!')
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.15/vue.js"></script>

<div id="example">
  <button type="button" @click="addToArray('cars')">Add to cars</button>
  <button type="button" @click="addToArray('invalidKey')">Add invalidKey</button>
  
  {{ cars }}
</div>

Comments

Your Answer

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.