Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to pass an integer variable as an array index in Vue.js 3?

I’ve struggled with an issue that seems really silly, but I could not find a solution for it.

The following variable declaration works:

export default {
    data() {
        return {
            random_number: 1,
            random_array: ['A','B','C'],
        }
    }

However, if I try to declare a third variable that accesses random_array, as in the two examples below, it doesn’t work:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export default {
    data() {
        return {
            random_number: 1,
            random_array: ['A','B','C'],
            random_var: random_array[1],
        }
    }
export default {
    data() {
        return {
            random_number: 1,
            random_array: ['A','B','C'],
            random_var: random_array[random_number],
        }
    }

I have tried referencing the arrays as this.random_array[1] or this.random_array[this.random_number], but neither have worked.

It seems like a simple syntax issue, but I couldn’t figure it out or find the solution online.

>Solution :

You can’t refer to an object within this same object. It’s like doing this:

const myObj = {
  firstName: 'Micheal',
  lastName: 'Scott',
  name: firstName + lastName, // these variables doesn't exist
  // or even
  name: myObj.firstName + myObj.lastName, // the myObj variable isn't created yet, you can't access it from itself
}

Your solution is simply to put your values inside variables before doing the return:

data() {
  const myNumber = 1;
  const myArray = ['A','B','C'];

  return {
     random_number: myNumber,
     random_array: myArray,
     random_var: myArray[myNumber],
  }
}

Note: if you name your variable with the same name as the object attribute, you can use shorthand property initalizer to shorten your code:

data() {
  const random_number = 1;
  const random_array = ['A','B','C'];

  return {
     random_number, // same as doing "random_number: random_number,"
     random_array,
     random_var: random_array[random_number],
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading