javascript - 使用重复键过滤映射结果

标签 javascript node.js map-function

我有一个命令处理程序,它使用一个映射,其中包含从用户命令文件夹和通用 comm 文件夹分配的命令。用户可以添加自己的命令。 map 过滤器使用文件内的名称进行过滤,这也是调用它们的方式。如果有多个同名的,如何进行比较? Afaik map 无法做到这一点,担心我必须全部重做。

起初我试图为每个用户分配它自己的 map

 client.User1.get(command, argument);
 client.User2.get(command argument);

这真的是正确的做法吗?我正在使用启用了命令名称的 .JSON 进行初始比较。在一些代码下方,您可能会说我经验不足。

const assignedChannels = client.opts.channels.slice(0);
assignedChannels.unshift('#basiccommands');
const rootForCommands = "./commands";
client.commandCall = new Map();

for (const channelspecificDir of assignedChannels) {

 const commandFiles = fs.readdirSync(`${rootForCommands}/${channelspecificDir}`);

 for (const file of commandFiles) {
     const commandCollection = require(`${rootForCommands}/${channelspecificDir}/${file}`);
     //sets a new item in the collection.
     //Key of map as command name and the value the function to send message and argument true or false
     client.commandCall.set(commandCollection.name, commandCollection);

     const currentProfile = JSON.parse(fs.readFileSync(`./userProfiles/${channel}.json`, 'utf8'));
     if (!currentProfile.all_commands.includes(commandPre)){
         return console.log("Command does not exist");
     } 
     try {
        client.commandCall.get(commandPre, argU).execute(channel, argU);
     } catch (error) {
         console.log('command broke');
         console.error(error);
     }

我以前的方法是将用户特定文件夹和通用命令文件夹分配给 map ,并在每次迭代结束时更改 map 对象的名称。但由于某种原因,这不起作用。

最佳答案

实际上,您可以使用符号作为 map 的键

const map = new Map()
map.set(Symbol(‘the same name’), value1)
map.set(Symbol(‘the same name’), value2)

您可以为 Map 的键使用任何值,甚至是对象和函数

map.set({}, value3)
map.set({}, value4)

在所有前面的表达式中,我们为 Map 的键获取不同的值(链接)。

顺便说一句。注意 const some = require(‘some_file_name’)require() 缓存一个文件名的值。因此,如果您的文件可能在运行时更新并且您需要阅读这些更新,则不应使用“require()”。它只适用于导入模块和静态值(例如配置)

关于javascript - 使用重复键过滤映射结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59129490/

相关文章:

javascript - 从浏览器发送 http 请求时缺少授权 header

javascript - 在 Javascript 中不使用 for 循环的等效函数?

javascript - 逻辑或代替三元

javascript - 有没有办法在 Python 中编写类似 lambda 的对象,就像在 JS 中一样

javascript - 尝试获取 process.env node.js 时出现 SyntaxError : Unexpected token .

SML map 功能

swift - Swift 中的链接方法

javascript - 如何在 div(或类似的东西)上使用 ngChange

javascript - jQuery 事件回调速度 : Anonymous vs. 命名函数

javascript - 将 node.js 更新为 0.12 header 错误