Can I use a dynamic value to access a specific array in Vue.js?

635 Views Asked by At

I've been trying to figure out how to do this, but can't seem to get it to work. I have created a function that is being called when I click a component using v-on:click. I am also trying to pass in a value that I can then use to access a particular array that is coming in the form of data from a backend.

Here is the function in the component:

<v-card
  @click="getContent('topSellers')"
 >

I am then passing the 'topSellers' value as an "id" into the function that is being used to get access the exact array that I am looking for:

getContent(id) {
      this.accordion = this.data.id;
      console.log("data", id);
    }

First of all, this.data.topSellers works. And I am seeing that the id value is correct in the console. Obviously, this is not working because id is currently a string, but I don't know how to fix that issue. Any help would be appreciated!

2

There are 2 best solutions below

2
On

You need this.data[id] instead of this.data.id.

See property accessors on MDN for reference.

data[id] will access the property of data with the name of the value of id, in your case topSellers. So data.topSellers is equivalent to data["topSellers"]

0
On

[] allows you to access objects with variables.

It is recommended to handle exceptions because the variable received is not safe.

getContent(id) {
  const accordion = this.data[id] || null;
  if(accordion){
    console.log("data", accordion);
    this.accordion = accordion;
  }
}