首页 > 解决方案 > 返回具有给定短语(数组)值的键

问题描述

我对 JavaScript 数组有疑问。我正在尝试创建一个函数,该函数根据特定的参数返回具有该参数的值的键。

我试过的代码:

    for(let i in client.commands.size) {
        let filteredCommands = client.commands.filter(cmd => cmd[i].help.cmdCategory = arg).map(c => c.name)
        console.log(filteredCommands)
        embed.addField(`${filteredCommands.help.name}`, `**Description:** ${filteredCommands.help.desc}\n**Usage:** \`${client.prefix}${filteredCommands.help.usage}\`\n**Exxample Usage:** ${filteredCommands.help.exampleUsage}`, false)
    }

client.commands它是一个数组,键是命令的名称,命令键中的值(例如。ping)命名cmdCategoryhelp子键中,并且参数和下一个返回键中的值需要满足此条件。(例如:如果键值cmdCategory具有 value fun,则返回符合此条件的键。这里有什么想法吗?还是谢谢。

标签: javascriptarraysdiscorddiscord.js

解决方案


如果您的对象客户端看起来像此示例,那么您可以尝试一下

let arg = 'sh'

let client = {
	commands: [
  	[
    	{
      	help: {
          cmdCategory: 'bash',
          name: 'some bash name',
          desc: 'description for bash'
        }
      }, 
    	{
      	help: {
          cmdCategory: 'sh',
          name: 'some sh name',
          desc: 'description for sh'
        }
      }
    ]
  ]
}

// reduce from [[{}, {}]] to [{},{}]
let commands = client.commands.reduce((prev, next) => {
	return prev.concat(next)
})

let filteredCommands = commands.filter(command => command.help.cmdCategory === arg)
console.log(filteredCommands)

filteredCommands.forEach(cmd => {
/* embed.addField(`${cmd.help.name}`, `**Description:** ${cmd.help.desc}\n**Usage:** \`${client.prefix}${cmd.help.usage}\`\n**Exxample Usage:** ${cmd.help.exampleUsage}`, false) */
})

// OR you can do this:
filteredCommands = []

client.commands.forEach(cmd => {
    cmd.forEach(item => {
        if (item.help.cmdCategory === arg) {
                filteredCommands.push(item)
            }
        })
})

console.log(filteredCommands)


推荐阅读