0

Using JS in conjunction with a JSON file to turn a room ID into the room information.

function rooms(roomID) {
    const roomsDB = require("./rooms.json")
    let roomsID = "r".concat("", roomID).toString()
    console.log(roomsDB.roomsID)
}

rooms(46)

This is the function I'm using to turn the ID into the info, and the rooms.json file is as follows:

{
    "r46":"house"
}

Ideally, this would log house into the console, but I only get undefined. Why isn't the JSON object being called properly?

cyliim
  • 39
  • 7

1 Answers1

1

To dynamically access an object property by name in a string variable you need to use brackets:

roomsDB[roomsID]

The dot (roomsDB.roomsID) is just like roomsDB["roomsID"], it doesn't substitute the variable.

Tobias K.
  • 2,997
  • 2
  • 12
  • 29