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

Trying to use a variable in a json file path – javascript

I’m trying to use a variable to access a field in my json file,
how do I do something like this?
js:

let file = require('./file.json')
let someVar = 'firstField'
console.log(file.firstObject.{someVar})

json:

{
  "firstObject": {
     "firstField":"firstValue",
     "secondField":"secondValue",
     "thirdField":"thirdValue",
  },
  "otherObject": {
     "otherField":"otherValue"
  }
}

desired outcome :

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

'firstValue'

>Solution :

obect[str] is what you looking for.
Your code should look like this:

let file = require('./file.json')
let someVar = 'firstField'
console.log(file.firstObject[someVar])
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