-1
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?

harsh panday
  • 83
  • 1
  • 10
  • 1
    `x` is a completely separate variable, so why do you expect in as a property of `n[0]`? Why aren't you just doing `n[0].x = this.oa`? – gre_gor May 24 '22 at 21:41
  • Basically, I am creating a graph, for that, I want to take user input and create that graph according to that. Here **oa** will have value Organizations (input by user), so when I don ```x=this.oa``` x will have the value Organizations, so I was thinking shouldn't ```console.log(n[0].x)``` give the same out put as ```console.log(n[0].Organizations)``` as value of x is Organizations? – harsh panday May 24 '22 at 21:46

1 Answers1

1

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.

M. Foote
  • 26
  • 2