首页 > 解决方案 > 搜索对象数组以匹配输入

问题描述

所以,我正在尝试做一些事情,但我正在碰壁,我确信这只是由于我的经验不足。

在下面的代码中,我试图将用户输入的内容 (!activate [card name]) 用于集换式纸牌游戏 (Bakugan),并让系统从全小写、无空格格式中查找卡片。我有一个单独的 cardlist.js 文件,其中将卡片设置为对象。我尝试了很多不同的方法,但我不断收到“____ 不是函数”,或者由于某种原因它无法在卡片列表文件中找到该项目。我知道我在尝试的几个小时里一直在围绕它跳舞。

const Discord = require("discord.js");
const botconfig = require("../botconfig.json");
const cardlist = require('../cardlist.js');

module.exports.run = async (bot, message, args) => {
    //console.log("works");
    //let aUser = `${message.author}`;
    let aCard = message.content.slice(10);
    oCard = Object.filter(function(cardlist){ 
        return cardlist.name === aCard });
    if (aCard === oCard) {
        console.log('Cards match!');
     } else {
         console.log(`Cannot find ${aCard}`)
     }
    }

module.exports.help = {
    name: "activate"
}

这是使用命令处理程序。我有许多其他命令可以正常使用它。代码一直有效,直到我试图让 aCard 和 oCard 匹配。我还尝试在卡片列表中搜索与用户输入的卡片名称相匹配的条目。下面是我对 cardlist.js 的布局

const cardlist = {
    pyrushyperdragonoid: {
        image: 'https://bakugan.wiki/wiki/images/thumb/3/3b/Hyper_Dragonoid_%28Pyrus_Card%29_265_RA_BB.png/250px-Hyper_Dragonoid_%28Pyrus_Card%29_265_RA_BB.png',
        name: 'Pyrus Hyper Dragonoid',
        faction: 'Pyrus',
        energy: 1,
        BPower: '400',
        Type: 'Evo',
        Damage: 6,
        Effect: ':redfist: : +300 :Bicon: and +3:attackicon:'
    },
    dragosfury: {
        name: 'Drago\'s Fury',
        Energy: 2,
        Type: 'Action',
        Effect: '+4:attackicon:. Fury: If you have no cards in hand, +:doublestrike:'
    }
}

因此,例如:1)用户输入命令“!activate pyrushyperdragonoid” 2)我希望机器人自动剪掉输入中的“!activate”。(正确完成) 3) 机器人应该获取该条目并在 cardlist.js 中搜索它并检索该卡片列表的所有其他部分。4) 我还没有在这段代码中完成它,但我将使用 RichEmbed 来显示检索到的所有信息。

我希望这一切都有意义!感谢您提前提供的所有帮助。

标签: javascriptnode.jsdiscord.js

解决方案


Object.filter不存在,即使它存在:什么是Object

由于您有一个命令处理程序,您的代码在这里只能从它接收“参数”,即不是整个消息,而只能是 bang 命令(这里!activate)之后的内容,这将避免几乎无法理解的.slice(10). 反正。

您不想明显匹配人类可读的名称("Pyrus Hyper Dragonoid"),您想匹配键名(pyrushyperdragonoid,最好不要有阅读障碍)。您可以像任何对象一样处理它,用括号表示键:

// aCard sounds like an object of the same nature as oCard, but it's just a string
var userInput = message.content.slice(10);
var oCard = cardlist[userInput];
// then you can test
if (oCard) {
  console.log(`You legitimately chose to activate ${oCard.name}!`);
  // here oCard is a sub-object of cardlist, such as { image: '...', name: '...', faction... }
} else {
  console.log(`No mighty beast answered to the name ${userInput}!`);
  // here oCard is undefined
}

推荐阅读