Search code examples
javascriptnode.jsconfiguration-files

Use String to Read Config File Variable


I have a config file (leaderboard.json) that looks like this:

{
    "usercount<@386679122614681600>": 0
}

I am trying to read the value of that variable (so it would be 0) in my index.js file which looks like this:

var LEADERBOARD = require('./leaderboard.json');
const usercount = 'usercount'+user
var countvalue = LEADERBOARD.usercount
console.log(countvalue)

I essentially want countvalue to return 0 but I can't simply use LEADERBOARD.usercount<@386679122614681600> since that name will be changing.

Basically, I'm wondering whether there is a workaround to where I can read my config file variable using a string I create.


Solution

  • You need to use bracket notation for that.

    var countvalue = LEADERBOARD[usercount]

    Here's an example:

    const foo = {
      bar123: 'baz'
    }
    
    const prop = 'bar' + 123
    console.log(foo[prop])