简体   繁体   中英

Return keys that have value with the given phrase (array)

I have problem with JavaScript array. I am trying to create a function that, according to a particular arg, returns keys with a value that has that arg.

The code I tried:

    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 it's a array who key is name of command, and value in command key (example. ping ) named cmdCategory is in help subkey and need value same in argument and next return keys which meet this condition. (for example: if key value cmdCategory have value fun , then return keys who meet this criteria. Any ideas for here? Thanks anyway.

If your object client looks like this example then you can try it

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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