cs09
cs09

Reputation: 100

Getting a value in a .json file using a constant to represent the value's name

I am making a discord bot, and I have a config file named config.json as follows:

{
    "token":"TokenPlaceholder",
    "prefix":"a.",
    "devPrefix":"+."
}

In my main index.js file I have this code that gets the prefix type dynamically from a different command file:

const commandPrefixType = botClient.commands.get(commandName).prefixType;

I require config.json like this: const CONFIG = require('./config.json');

The value of the constant commandPrefixType will either be prefix or devPrefix. How can I use this constant to dynamically get the value of said prefixType from config.json?

For example, if the command's prefixType value is 'devPrefix', then how can I get the value '+.' without using an if/else or switch block? (I want it to be dynamic because I plan on adding more prefixes in the future).

Thanks

Upvotes: 1

Views: 1377

Answers (1)

Rakox
Rakox

Reputation: 66

I think the best solution to your problem is to access your object values by using bracket ([]):

const CONFIG = require('./config.json');
const commandPrefixType = botClient.commands.get(commandName).prefixType;

// Access to the prefix
const commandPrefix = CONFIG[commandPrefixType];
console.log(commandPrefix)

Hope this helps!

Upvotes: 4

Related Questions