如何计算Jquery中JSON数据具有特定值的键的次数



我的问题涉及以下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)

我感谢回复的用户提供的帮助。

出于某种原因,当JSON写在变量中时(如回复中所示(,我可以处理它,但当从ajax进程返回相同的JSON时,我不能处理它。

通过改用XML,我的问题终于得到了解决。

<matches>
<result country = "USA" postcode = "9011" />
<result country = "USA" postcode = "9011" />
<result country = "UK" postcode = "BB3" />
</matches>

var countcountcountry=$(xml_result(.find('sult[country="usa"]'(.length;

退货:2

使用reduce绝对是我的建议。如果你有兴趣统计其他国家,你可以在下面这样做:

const response = {
"matches": [{
"country": "USA",
"postcode": "9011"
}, {
"country": "USA",
"postcode": "9010"
}, {
"country": "UK",
"postcode": "BB3"
}]
}
const countryCount = response.matches.reduce((acc, match) => {
const country = match.country;
if (!acc[country]) {
acc[country] = 1;
} else {
acc[country]++;
}
return acc;
}, {});
// print USA and UK
console.log(countryCount.USA);
console.log(countryCount.UK);

试试这个:

var jsonObj = {"matches":[
{
"country":"USA", 
"postcode":"9011"
},
{
"country":"USA", 
"postcode":"9010"
},
{
"country":"UK", 
"postcode":"BB3"
}
]};
var count = 0;
for (var i in jsonObj.matches) {
(jsonObj.matches[i].country == 'USA') ? count = count+1 : 0;  
}
console.log("Country count with USA :", count);

使用Array#filter()和结果的长度对于这个用例来说相当简单

let data = {"matches":[{"country":"USA", "postcode":"9011"},{"country":"USA", "postcode":"9010"},{"country":"UK", "postcode":"BB3"}]}
let us_count = data.matches.filter(({country:c}) => c === 'USA').length
console.log(us_count)

最新更新