Restricting the frequency at which a specific key value is allowed to appear in JSON documents

Within my JSON file, there is an array structured like this:

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

I have a requirement to restrict the number of commands for each user (identified by their user_id) to a maximum of 3. I understand that I need to iterate through each object in the array, but I am unsure how to proceed from there.

The desired outcome would resemble something like this:

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

Answer №1

To monitor the number of commands executed by each user, you can create an object that tracks these numbers and then easily verify if a specific user has exceeded the command limit.

let commandsList = [
   {
     "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 userCommandsTracker = {};
 
 commandsList.forEach(command=>{
  if(!userCommandsTracker.hasOwnProperty(command.user_id))
    userCommandsTracker[command.user_id] = 0;
  userCommandsTracker[command.user_id]++;
 });

// Check if the specified user has exceeded the command limit
if(userCommandsTracker["83738373"] > 3){
  console.log("User has performed too many commands!");
}

Answer №2

Two functions were developed: one to determine if the maximum limit has been surpassed and another to display an error message if needed.

var userID = "83738373";
var arrayOfCommands = {
     "commands": [
       {
          "user": "Rusty",
         "user_id": "83738373",
         "command_name": "TestCommand",
         "command_reply": "TestReply"
       }
     ] 
  }

//Function to check if maximum commands exceeded
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 error message
function maximumExceeded(){
    //insert your code here
    message.reply("You cannot make more than 3 commands.");
}

//Execution of the code begins here
var hasExceeded = exceededMaximumComands(userID);

//Checking the outcome
if (hasExceeded){
  maximumExceeded();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The issue with Grid component in Nested Single file Component

I'm currently working on creating a grid component in Vue to set up a sortable and searchable chart using Single File Component. I've also integrated vue-router into the project. Below are my two .vue files. At the moment, I can only see the sear ...

Watching the $scope variable using $watch will result in triggering even when ng-if directive is used, displaying

Encountering an unusual behavior in AngularJS that may appear to be a bug, but there could be a logical explanation. A certain value is being passed to a directive as an attribute. Within this directive, the parameter is being watched using $scope.$watch. ...

What is the process for generating an alert box with protractor?

While conducting tests, I am attempting to trigger an alert pop-up box when transitioning my environment from testing to production while running scripts in Protractor. Can someone assist me with this? ...

I am currently facing an issue with retrieving the class value that is being generated by PHP code

I am currently facing an issue with jQuery and PHP. Whenever I attempt to target the click event on the class ".id_annonce" in the dynamically generated PHP code, it doesn't retrieve the exact value of what I clicked. Instead, it always gives me a fi ...

When text exceeds multiple lines, display an ellipsis to indicate overflow and wrap only at word boundaries

Here is an example snippet of my code: <div class="container"> <div class="item n1">Proe Schugaienz</div> <div class="item n2">Proe Schugaienz</div> </div> and I am using the following jQuery code: $(&apos ...

I'm wondering if there is a method for me to get only the count of input fields that have the class "Calctime" and are not empty when this function is executed

Currently, I am developing an airport application that aims to track the time it takes to travel between different airports. In this context, moving from one airport to another is referred to as a Sector, and the duration of time taken for this journey is ...

Timeout error for WebSocket connection on JavaScript client

My first attempt at using websockets is not going as planned. Since my IP address changes frequently, I decided to make the following websocket call on the server-side: $echo = new echoServer("myurl.com","9000"); On the client-side, I'm making the f ...

What are the steps for implementing CORS?

I recently attempted to set up Ajax calls and stumbled upon the following code snippet: <!DOCTYPE html> <html> <body> <p id="demo">Let AJAX update this text.</p> <button type="button" onclick="loadDoc()">Updat ...

What is the best way to bypass TS1192 when incorporating @types/cleave.js into my Angular application?

Using cleave.js (^1.5.2) in my Angular 6 application, along with the @types/cleave.js package (^1.4.0), I encountered a strange issue. When I run ng build to compile the application, it fails and shows the following errors: ERROR in src/app/app.component. ...

Traverse through an array of pictures and add the data to a Bootstrap placeholder within HTML markup

In my quest to create a function that populates placeholders in my HTML with images from an array, I am encountering a problem. Instead of assigning each image index to its corresponding placeholder index, the entire array of images is being placed in ever ...

Display contents from a JSON file

I need to extract unique locality values from a JSON file in Python, but my current code is only printing the first few entries and not iterating through all 538 elements. Here's what I have: import pandas as pd import json with open('data.json ...

Is there a way for me to receive a success message when I successfully set data in Firebase?

I want to retrieve the orderId after successfully adding an order to the Realtime database using angularfirestore. What should I use after set() method to return the orderId? The structure of my order object is as follows: const orderObj: Order = { pay ...

Encountering issues with Vue routing while utilizing webpack. The main page is functional, however, subpaths are resulting in

Before implementing webpack, my vue routing was functioning properly. However, I encountered several loader issues and decided to use webpack. After setting up webpack, the main page loads correctly, but all of my routes now result in a 404 error. I have ...

Display all months on mobile screen using Mui DesktopDatePicker

Looking for a Better Date Range Picker I've been working on a project that requires a date range picker, and I opted to use the Mui date range picker. While it works well on desktop, I encountered an issue with mobile view where only one month is sho ...

Creating a complex array structure using checkbox inputs within an Angular application

In my Angular application, I have a list of checkboxes that are dynamically generated using nested ng-repeat: <div ng-repeat="type in boundaryPartners"> <div class="row" ng-show="showBPtype[$index]"> <div class="col-xs-12"> ...

Include additional data in the FormData object before sending it over AJAX requests

Currently, I am utilizing AJAX to store some data. The primary concern I have is figuring out how to incorporate additional information into the FormData object along with what I already have. Below is the function that I'm using. Could you assist me ...

The powerful combination of Newtonsoft JSON and Graph API

Utilizing Newtonsoft JSON, I deserialize responses from the Facebook Graph API. For instance, when parsing user posts, the response looks like this: data": [ { "story": "", "created_time": "", "id": "" }] To handle this data, I ...

Implementing Dynamic CSS Styles in AngularJS

Essentially, I am facing a challenge on my page where a control needs to toggle two different elements with two distinct CSS classes upon being clicked. While I have successfully managed to toggle one of the controls, the other remains unchanged. Here is ...

Navigate through an array of objects to retrieve particular key/value pairs

I have an item that has the following structure: [ { "title": "Job Title", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385d55595154785d55595154165b5755">[email p ...

Having trouble with the JSON response while implementing AngularJS

Recently, I've started working with angularjs and ran into an issue where the data is not loading on the page when pulling JSON from a Joomla component. Strangely enough, everything works perfectly fine when I retrieve the data from a getcustomers.ph ...