限制JSON中某个键的值的次数



我的json文件中有一个数组,如下:

{
 "commands": [
   {
     "user": "Rusty",
     "user_id": "83738373",
     "command_name": "TestCommand",
     "command_reply": "TestReply"
   }
 ] 
}

等等。我想将命令量限制为某个用户(由user_id识别(到3个命令。我知道我需要首先遍历每个对象,但要坚持如何完成下一部分。

我希望它看起来与此相似:

for (let i = 0; i < arrayOfCommands.commands.length; i++) { 
  if (arrayOfCommands.commands.user_id appears more than 3 times) {
   return message.reply("You cannot make more than 3 commands.");
  }
}

您可以创建一个对用户ID命令数量的对象。然后只需检查对象即可查看给定用户是否命令太多。

let commands = [
   {
     "user": "Rusty",
     "user_id": "83738373",
     "command_name": "TestCommand",
     "command_reply": "TestReply"
   },
   {
     "user": "Rusty",
     "user_id": "83738373",
     "command_name": "SecondCommand",
     "command_reply": "TestReply"
   },
   {
     "user": "Rusty",
     "user_id": "83738373",
     "command_name": "ThirdCommand",
     "command_reply": "TestReply"
   },
   {
     "user": "Bart",
     "user_id": "83738233",
     "command_name": "ThirdCommand",
     "command_reply": "TestReply"
   },
   {
     "user": "Rusty",
     "user_id": "83738373",
     "command_name": "FourthCommand",
     "command_reply": "TestReply"
   }
 ];
 
 let userCommands = {};
 
 commands.forEach(command=>{
  if(!userCommands.hasOwnProperty(command.user_id))
    userCommands[command.user_id] = 0;
  userCommands[command.user_id]++;
 });
// Then quickly check if they have too many commands
if(userCommands["83738373"] > 3){
  console.log("Too many!");
}

我创建了两个函数:一个返回简单布尔值以检查是否超过了最大值,另一个要执行错误消息。

var userID = "83738373";
var arrayOfCommands =  {
     "commands": [
       {
          "user": "Rusty",
         "user_id": "83738373",
         "command_name": "TestCommand",
         "command_reply": "TestReply"
       }
     ] 
  }
//Function to return a simple boolean
function exceededMaximumComands(user){
    var count = 0;
    for (let i = 0; i < arrayOfCommands.commands.length; i++) { 
      if (arrayOfCommands.commands.user_id === userID) {
          count++;
          if(count > 2){ 
              return true;
          }
      }
    }
}
//Reusable function for throwing error message
function maximumExceeded(){
    //change this with your code
    message.reply("You cannot make more than 3 commands.");
}
//Where the code executes
var hasExceeded = exceededMaximumComands(userID);
//Check the result
if (hasExceeded){
  maximumExceeded();
}

最新更新