1

For my bot in discord, I would like a !help command that loops through all commands, gets the name, and returns them in a message back to the user. I have created fs to loop through my /commands/ folder:

for (const file of commandFiles) {
    const command = require(`./commands/${file}`);
    client.extraCommands.set(command.name, command);
}

console.log(client.extraCommands);

Returns a Collection Map that looks like: (cropped for sake of simplicity)

Collection [Map] {
  'args-info' => {
    name: 'args-info',
    execute: [Function: execute]
  },
  'channel-info' => {
    name: 'channel-info',
    execute: [Function: execute]
  }

All I need is to store the name of each command into an array.

I've tried looping through to get the key but that doesn't seem to work...

Thanks in advance for any help

1
  • If it's a Map, you can loop through for(const key of client.extraCommands.keys()){/* Add key to an array */} or just use client.extraCommands.keys() since it's an iterator Commented Mar 9, 2020 at 21:20

3 Answers 3

3

Looks like the key names are your command names, so this should do the trick.


let keys = Array.from(client.extraCommands.keys());

Sign up to request clarification or add additional context in comments.

Comments

1

So, at first, I thought I should make a loop to go through all files and get the 'name' attribute. However, the .keys() returns an array for all properties inside the map Documentation

1 Comment

I never said you need to loop yourself to get the keys.
0

Both lines of codes will return the same result as you want.

[...client.extraCommands.keys()] //using map keys
[...client.extraCommands.values()].map(({name})=> name); // using key 'name' from each map value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.