【问题标题】:Counting how many times a value of a certain key appears in JSON计算某个键的值在 JSON 中出现的次数
【发布时间】:2017-04-18 19:47:22
【问题描述】:

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

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

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

【问题讨论】:

  • 所以你算数并忽略?
  • 您的标题和问题文本不完全匹配。 stackoverflow.com/q/17615364/215552 涵盖了获取计数。如果您想获取具有特定 userId 的命令,stackoverflow.com/q/13964155/215552 涵盖了这一点。
  • @MikeMcCaughan 我同意你的观点,你链接的 2 个帖子可以回答这个问题,但我不会说标题和问题不匹配。根据标题,OP 希望计算对象数组上特定属性的特定值出现的次数。我认为问题正文中没有任何其他说明。
  • @mhodges “我想将命令的数量限制为 3 个命令。”暗示了我们不知道的其他要求,这些要求应该会影响最终的答案。例如,正如 epascarello 在第一条评论中所建议的那样,也许 OP 想要获取前 3 个命令并忽略其余命令。也许他们想按 user_id 分组并获取您已经演示过的计数(并且在整个站点的许多其他答案中都有演示)。基本上,我们不知道,因为 OP 没有回应。
  • @MikeMcCaughan 啊,真的。我不是那样读的,但我现在完全明白你在说什么了。

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


【解决方案1】:

您可以通过在 Array 原型上使用 .reduce() 方法来做到这一点。这个想法是通过 commands 数组并生成 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"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    相关资源
    最近更新 更多