How to loop through JSON file with NodeJS
我在一个不和谐的机器人上工作,命令高级成员。
买主:杰森:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | buyers.json: { "buyers": [ { "id":"331499609509724162" }, { "id":"181336616164392960" }, { "id":"266389854122672128" } ] } |
代码段:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | case"spotify": var uID = message.author.id; for (let i = 0; i < ftpr.buyers.length; i++) { if (uID === ftpr.buyers[i]) { var _embed = new Discord.RichEmbed() .setTitle("Spotify") .addField("Username","[email protected]") .addField("Password","ithastobe8") .setColor(0x00FFFF) .setFooter("Sincerely, LajgaardMoneyService") .setThumbnail(message.author.avatarURL); message.author.send(_embed); console.log(message.author +" Just used the command !spotify") } } break; |
除了for循环和if语句之外,其他一切都可以工作。好像没有拿到身份证。
1 | var fptr = require("./buyers.json"); |
编辑:我的JSON文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | { "buyers": [ { "id":"331499609509724162" }, { "id":"181336616164392960" }, { "id":"266389854122672128" } ] } |
它有一些人的身份证。在我的app.js中,
您正在将我假定为字符串的uid与数组中的每个对象(包含字符串)进行比较。
尝试比较买家对象的ID属性:
1 | if (uID === ftpr.buyers[i].id) { } |
确保
您可以通过在开关盒之前拥有一个包含ID的字符串数组来简化代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | const ids = ftpr.buyers.map(b = b.id);//this is now ["331499609509724162",...] case"spotify": if (ids.includes(message.author.id)) { var _embed = new Discord.RichEmbed() .setTitle("Spotify") .addField("Username","[email protected]") .addField("Password","ithastobe8") .setColor(0x00FFFF) .setFooter("Sincerely, LajgaardMoneyService") .setThumbnail(message.author.avatarURL); message.author.send(_embed); console.log(message.author +" Just used the command !spotify") } break; |