首页 > 解决方案 > 如何计算 JSON 数据在 Jquery 中具有特定值的键的次数?

问题描述

我的问题涉及以下 JSON 数据:

{"matches":[
  {
    "country":"USA", 
    "postcode":"9011"
  },
  {
    "country":"USA", 
    "postcode":"9010"
  },
  {
    "country":"UK", 
    "postcode":"BB3"
  }
]}

谁能告诉我如何检索 country = USA 的次数?

在当前情况下,所需的输出是:2。

我一直在寻找如何做到这一点,但一直找不到解决方案。

在此先感谢您的帮助。

问候,

标签: javascriptjqueryjson

解决方案


只需循环并计数。您可以使用reduce()它并在值与您想要的匹配时增加计数。

let o = {"matches":[{"country":"USA", "postcode":"9011"},{"country":"USA", "postcode":"9010"},{"country":"UK", "postcode":"BB3"}]}

let num_usa = o.matches.reduce((count, el) => {
  if (el.country === 'USA') count++
  return count
}, 0)
console.log(num_usa)


推荐阅读