计算JSON中具有某些属性的元素数 [英] Count number of elements with certain properties inside JSON
本文介绍了计算JSON中具有某些属性的元素数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些JSON数据:
I have some JSON data:
{"humans": [
{ "firstName" : "Paul", "lastName" : "Taylor", "hairs": 2 },
{ "firstName" : "Sharon", "lastName" : "Mohan", "hairs": 3 },
{ "firstName" : "Mohan", "lastName" : "Harris", "hairs": 3 },
{ "firstName" : "Deborah", "lastName" : "Goldman", "hairs": 4 },
{ "firstName" : "Mark", "lastName" : "Young", "hairs": 4 },
{ "firstName" : "Tom", "lastName" : "Perez", "hairs": 4 }
//and so on...
]}
我希望能够计算2根头发,3根头发等的所有人数.现在我正在使用jQuery.each()
加上可以正常工作的递增计数数组.
但是我想知道是否有更简单的方法来做到这一点.
I want to be able to count all people with 2 hairs, 3 hairs etc. Right now I am using jQuery.each()
plus an incrementing count-array which works fine.
But I was wondering if there is an easier way to do this.
更新: 附加代码说明我现在正在做什么:
UPDATE: Additional code saying what I am doing right now:
var results = eval(data.humans);
var count_array = [0, 0, 0, 0, 0, 0, 0];
$(results).each(function() {
if (this.hairs == 1) {
count_array[0]++;
}
if (this.hairs == 2) {
count_array[1]++
}
if (this.hairs == 3) {
count_array[2]++
}
if (this.hairs == 4) {
count_array[3]++
}
if (this.hairs == 5) {
count_array[4]++
}
if (this.hairs == 6) {
count_array[5]++
}
if (this.hairs == 7) {
count_array[6]++
}
});
推荐答案
You can use the filter
function to filter an array of objects :
var data = {...}
data.humans.filter(function(o) { return o.hairs == 2 }).length
//Return the number of humans who have 2 hairs
看看小提琴
这篇关于计算JSON中具有某些属性的元素数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文