Skip to content Skip to sidebar Skip to footer

Counting How Many Times A Value Of A Certain Key Appears In Json

I have an array within my JSON file which looks as follows: { 'commands': [ { 'user': 'Rusty', 'user_id': '83738373', 'command_name': 'TestCommand', 'comman

Solution 1:

You can do this by using the .reduce() method on the Array prototype. The idea is to go through the commands array and generate a key/value pair of the userIds and the number of commands executed by that user. The structure would look like the following:

{"83738373": 3, "83738334": 2}

You can then check against the userCommandCounts to determine whether a user can execute another command or not.

var data = {
  "commands": [{
      "user": "Rusty",
      "user_id": "83738373",
      "command_name": "TestCommand",
      "command_reply": "TestReply"
    },
    {
      "user": "Jill",
      "user_id": "83738334",
      "command_name": "TestCommand",
      "command_reply": "TestReply"
    },
    {
      "user": "Rusty",
      "user_id": "83738373",
      "command_name": "TestCommand",
      "command_reply": "TestReply"
    },
    {
      "user": "Rusty",
      "user_id": "83738373",
      "command_name": "TestCommand",
      "command_reply": "TestReply"
    },
    {
      "user": "Jill",
      "user_id": "83738334",
      "command_name": "TestCommand",
      "command_reply": "TestReply"
    },
  ]
};

var userCommandCounts = data.commands.reduce(function (result, current) {
  if (!result[current["user_id"]]) {
    result[current["user_id"]] = 0;
  }
  result[current["user_id"]]++;
  return result;
}, {});

functioncanUserExecute (userId) {
  return !userCommandCounts[userId] || userCommandCounts[userId] < 3; 
}

console.log(canUserExecute("83738373"));
console.log(canUserExecute("83738334"));
console.log(canUserExecute("23412342"));

Post a Comment for "Counting How Many Times A Value Of A Certain Key Appears In Json"