javascript - 返回具有给定短语(数组)值的键
问题描述
我对 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
)命名cmdCategory
在help
子键中,并且参数和下一个返回键中的值需要满足此条件。(例如:如果键值cmdCategory
具有 value fun
,则返回符合此条件的键。这里有什么想法吗?还是谢谢。
解决方案
如果您的对象客户端看起来像此示例,那么您可以尝试一下
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)
推荐阅读
- javascript - 正确更新反应状态/组件?
- r - RQuantlib - 负利率的固定利率债券
- php - 如何通过行号从 CSV 文件中删除特定行?
- nginx - nginx - 通过 nginx 反向代理的两个域
- jquery - Fullcalendar V4,拖拽动态生成事件出错
- c# - XmlSerlializer 没有序列化类的所有属性
- swift - 应用程序崩溃相机设备后部:由于内存问题而终止
- python - 基于标签的重叠聚类(软聚类)
- delphi - Delphi 10.3.2 - 无法解析单元名称 System.Classes
- javafx - javafx 如何获取特定的 tabvleview 单元格索引?