问题描述
我试图找到解决“ json.find”问题以显示项目和价格的方法
例如
类型.shop basic kibble
机器人回复Name: Basic Kibble cost: k50
或输入.shop food
机器人回复Name:Food cost k10
在bot.js中
bot.on("message",({ author,channel,content }) => {
if (author.bot || !content.startsWith(prefix)) return;
const args = content.slice(prefix.length).split(" ");
const command = args.shift();
if (command === "shop") {
if (!args.length) return message.channel.send("You must specify an item!");
const input = args.join(" ");
const items = json.find((object) => object.name === `item`);
if (!items) return channel.send(`${input} isn't a valid item!`);
channel.send(`Name: ${items.name} Cost: k${items.cost}`);
}
});
解决方法
您在评论中说了以下内容:
“在shop.json文件 {"item": [ { "name": "Basic Kibble","cost": 50 },{ "name": "food","cost": 10 } ] }
中”
如果json是这个,则表示它是一个对象。您将需要使用:
const items = json.item.find(object => object.name === `item`)