简体   繁体   English

如何从discord.js中的Collection Map获取数据

[英]How to get data from Collection Map in discord.js

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.对于我不和谐的机器人,我想要一个 !help 命令,它循环遍历所有命令,获取名称,并在消息中将它们返回给用户。 I have created fs to loop through my /commands/ folder:我创建了fs来循环我的 /commands/ 文件夹:

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.我所需要的只是将每个命令的name存储到一个数组中。

I've tried looping through to get the key but that doesn't seem to work...我试过循环获取密钥,但这似乎不起作用......

Thanks in advance for any help在此先感谢您的帮助

看起来键名是你的命令名,所以这应该可以解决问题。


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

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

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但是, .keys()为地图文档中的所有属性返回一个数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM