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

Mapping an object in ReactJS: The ultimate guide

When I fetch user information from an API, the data (object) that I receive looks something like this: { "id":"1111", "name":"abcd", "xyz":[ { "a":"a", "b":"b", "c":"c" ...

Obtaining the correct information from an array using Ionic's Angular framework

I am currently working with an array of data that contains arrays within each item. I have been able to display the data as needed, except for the IDs. Approach Show arrays within the array Retrieve the IDs of the arrays (excluding the IDs inside the ar ...

The appearance of the circle in Safari is rough and lacks smoothness

My circle animation works perfectly on Google Chrome, but when I switch to Safari the edges appear faded and blurry. I tried adding "webkit" to fix it, but had no luck. Is there a compatibility issue with Safari and CSS animations? Here is my code: Snapsh ...

In a set of numbers with a specific maximum sum, find the pair of numbers that can be added together to achieve the maximum sum

Looking for a solution that finds pairs in an array with a sum less than the maximum value: def findPairs(arr, x): left = 0; right = len(arr)-1 result = 0 while (left < right): if (arr[left] + arr[right] < x): ...

Using the map method in JavaScript, merge two separate arrays to create a new array

In my ReactJS project, I have created two arrays using map function. The first array is defined as follows: const hey = portfolioSectorsPie.map(sector => sector.subtotal); const hello = portfolioSectorsPie.map(sector => sector.percentage) The value ...

The outcome of the AJAX RSS Reader remains unpredictable

Utilizing the AJAX RSS Reader (visit this link) for extracting RSS data from my URL: http://vtv.vn/trong-nuoc.rss In my php file (readRSS.php): <?php $url = ("http://vtv.vn/trong-nuoc.rss"); $xmlDoc = new DOMDocument(); $xmlDoc->load($url); $ ...

Get the JSON array by decoding the JSON data in PHP

I have a JavaScript function that creates a JSON array and uses an AJAX post method. How should this JSON array be decoded on the PHP side? Here is my JavaScript function: var invoices = {invoice: [{ "customerName" : "John" ,"reciptionName" : "Doe" ,"dat ...

Implementing a long press feature for a stopwatch in React

I'm facing a dilemma with this particular issue. Before reaching out here, I scoured the community and found numerous solutions for handling long press events in React, but they all seem to focus on click button events. Currently, I am devising a sto ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

Unexpected data type being returned by Swift .map function

I am attempting to convert two different arrays of doubles into an array of MKMapPoints. These arrays, x and y, are nested within another array that contains various data types like Strings and booleans. Here is the model: struct HostModel: Identifiable, ...

Error code E11000 is indicating that a duplicate key issue has occurred in the collection "blog-api.blogs" where the index "id_1" is

Issue with Error E11000 duplicate key error collection: blog-api.blogs index: id_1 dup key: { id: null } Encountering an error when trying to insert data after initially inserting one successfully. Referencing the blogSchema.js: const mongoose = req ...

Instructions for attaching an event listener to a Threejs Mesh Object with the help of threex dom events

var domEvents = new THREEx.DomEvents(camera, view.domElement); var div = document.createElement( 'div' ); div.setAttribute('data-remove','mesh1'); div.className = 'close-me'; var label = new THREE.CSS2DObje ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

Using Ajax to dynamically generate column headers in Datatables

Is there a way to create a header title from an ajax file? I've been trying my best with the following code: $('#btntrack').on('click', function() { var KPNo = $('#KPNo').val(); var dataString = & ...

Switch classes according to scrolling levels

My webpage consists of multiple sections, each occupying the full height and width of the screen and containing an image. As visitors scroll through the page, the image in the current section comes into view while the image in the previous section disappe ...

Troubleshooting your Meteor App on Nitrous.io with server-side debugging

I currently have a basic Meteor application up and running on a Nitrous box. I am interested in utilizing node-inspector for debugging the server-side part of my app, but I'm facing difficulty accessing the console as detailed here. The Meteor app is ...

Error message: Unable to access .exe file through HTML link

We have a need to include an HTML link on our intranet site that, when clicked, will open an .exe file that is already installed on all user machines. I attempted the following code: <a href = "C:\Program Files\Cisco Systems\VPN&bsol ...

Access the entire appsettings.json configuration data in string format

I am seeking a way to extract the complete contents of my appsettings.json file and parse it using NewtonSoft.JSON for full JSON path capabilities. The goal is to read the entire appsettings.json file as a string without specifying individual settings lik ...

What is the method to indicate JSON serialization in MVC without utilizing ActionResult return types?

When using ASP.NET MVC 5, you have the option to avoid using the "ActionResult" return type and instead define a more 'real' class for your methods. However, I've encountered an issue where MVC wants to return the .ToString() version of my o ...

Verify the validity of the user's input

Using knockout.js and knockout.validation, I have created a book view model with properties for the author's name and book title: function BookViewModel(bookObj) { var self = this; self.AuthorName = ko.observable(bookObj.AuthorName) ...