计算某个键的值在JSON中出现的次数

时间:2017-04-18 19:47:22

标签: javascript arrays json key-value key-value-coding

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

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

等等。我想限制某个用户(由user_id识别)到3个命令的命令数量。我知道我需要从循环遍历每个对象开始,但坚持如何完成这一部分。

1 个答案:

答案 0 :(得分:3)

您可以使用Array原型上的.reduce()方法执行此操作。我们的想法是通过命令数组并生成userIds的键/值对以及该用户执行的命令数。结构如下所示:

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

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



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"));
&#13;
&#13;
&#13;