javascript – 计算JSON中具有特定属性的元素数

前端之家收集整理的这篇文章主要介绍了javascript – 计算JSON中具有特定属性的元素数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一些 JSON数据:
{"humans": [
    { "firstName" : "Paul","lastName" : "Taylor","hairs": 2 },{ "firstName" : "Sharon","lastName" : "Mohan","hairs": 3 },{ "firstName" : "Mohan","lastName" : "Harris",{ "firstName" : "Deborah","lastName" : "Goldman","hairs": 4 },{ "firstName" : "Mark","lastName" : "Young",{ "firstName" : "Tom","lastName" : "Perez","hairs": 4 }
    //and so on...
]}

我希望能够计算所有拥有2根头发,3根头发等的人.现在我正在使用jQuery.each()加上递增计数数组,它可以正常工作.
但我想知道是否有更简单的方法来做到这一点.

更新:
附加代码说明我现在在做什么:

var results = eval(data.humans);
var count_array = [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]++
    }
});

解决方法

您可以使用 filter function过滤对象数组:
var data = {...}

data.humans.filter(function(o) { return o.hairs == 2 }).length
//Return the number of humans who have 2 hairs

看看fiddle

猜你在找的JavaScript相关文章