-1

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 :

'firstValue'
gregor
  • 3
  • 1

1 Answers1

0

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

let file = require('./file.json')
let someVar = 'firstField'
console.log(file.firstObject[someVar])
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49