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 can I use one variable with another in Vue JavaScript?

const n = this.prac
const x = this.oa
console.log(x)
console.log(n[0].x)

So n stores data from a JSON file with columns like Organizations, Title etc.
oa will have a value given as input by the user. Let’s suppose user inputs Organizations
I want to print n[0].x i.e n[0].Organizations
but when I do console.log(n[0].x) it print undefined
On the other hand console.log(n[0].Organizations) works fine.
What am I doing wrong? Can I not use x instead of Organizations?

>Solution :

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

When attempting to access data from an object with a variable, you can use bracket notation instead of dot notation.

So for you, you can do

const n = this.prac
const x = this.oa
console.log(x)
console.log(n[0][x])

Which should result in the value you’re looking for.

I found this wonderful answer here How can I access and process nested objects, arrays or JSON? that gives more details and background on why this works.

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