Reputation: 15
I'm creating a discord bot (using discord.js) I'm writing a help command using pages in embeds, I have the pages working fine - however, the problem seems to come when trying to get the data from the JSON. I have the JSON file setup in a larger config file, so it's nested inside of it. Each command has it's name attached to it
{
"other-json-data": "other data",
"commands": {
"rule": {
"info": "This command gives the rules",
"expectedArgs": "<number>"
},
"invite": {
"info": "Invite new users",
"expectedArgs": "<no-args>"
},
"flip": {
"info": "Flip a coin",
"expectedArgs": "<no-args>"
}
},
"other-json-data": "other data"
}
I need to get the data from the commands
area for each page.
I only have a integer input (from the page number), but I haven't got a clue how I would get the data from whatever command needs to be shown.
For something else in my project, I am using this to get the expectedArgs from the JSON object config.commands[arguments].expectedArgs
, where the config is just a reference to the JSON file, this works perfectly fine. The arguments is a string input (i.e. rule
), which returns whatever the info from that command.
However, would there be a way to get say the second one down (invite
). I've tried config.commands[pageNumber].expectedArgs}
, however, this doesn't seem to work. pageNumber would be an integer, so would it would get whatever value and then I could grab the expectedArgs
.
Upvotes: 0
Views: 77
Reputation: 361
You can get all keys from an object and select one using their index.
const json = {
"other-json-data": "other data",
"commands": {
"rule": {
"info": "This command gives the rules",
"expectedArgs": "<number>"
},
"invite": {
"info": "Invite new users",
"expectedArgs": "<no-args>"
},
"flip": {
"info": "Flip a coin",
"expectedArgs": "<no-args>"
}
},
"other-json-data": "other data"
}
const pageNumber = 1
// key will be a command name, e.g. 'invite'
const key = Object.keys(json.commands)[pageNumber]
const { expectedArgs } = json.commands[key]
console.log(`${key} expects ${expectedArgs}`)
Remember that indexes range starts at zero.
Upvotes: 1