javascript - 如何计算 JSON 数据在 Jquery 中具有特定值的键的次数?
问题描述
我的问题涉及以下 JSON 数据:
{"matches":[
{
"country":"USA",
"postcode":"9011"
},
{
"country":"USA",
"postcode":"9010"
},
{
"country":"UK",
"postcode":"BB3"
}
]}
谁能告诉我如何检索 country = USA 的次数?
在当前情况下,所需的输出是:2。
我一直在寻找如何做到这一点,但一直找不到解决方案。
在此先感谢您的帮助。
问候,
解决方案
只需循环并计数。您可以使用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)
推荐阅读
- python - Django - 使用 Celery 7 天后更新字段值
- json - 如何基于相等性检查在 Spark 中使用内部数组查询嵌套 json
- javascript - 如何一次为特定标签中的所有元素编写事件监听器?
- r - 如何根据是否具有先前值插入逻辑值?
- bluetooth-lowenergy - 蓝牙 LE _commands_ 的消息结构/语法是什么?
- git - 从损坏的标头恢复本地分支
- python - 看门狗函数的命令行参数
- ember.js - 选择文件后的操作
- ruby - 使用 Carrierwave 将图像从 png 转换为 jpg
- php - 在控制器 Magento 2 中获取当前产品信息?