计算某个键的值在JSON中出现多少次 [英] Counting how many times a value of a certain key appears in JSON

查看:226
本文介绍了计算某个键的值在JSON中出现多少次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON文件中有一个数组,如下所示:

I have an array within my JSON file which looks as follows:

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

,依此类推.我想将特定用户(由user_id识别)的命令数量限制为3个命令.我知道我需要首先遍历每个对象,但会停留在如何完成此部分上.

and so on. I want to limit the amount of commands to a certain user (recognized by the user_id) to 3 commands. I know I need to start by looping through each object but stuck at how to accomplish this part.

推荐答案

您可以使用

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}

然后您可以对照userCommandCounts进行检查,以确定用户是否可以执行其他命令.

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;
}, {});

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

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

这篇关于计算某个键的值在JSON中出现多少次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆