Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

javascript - Count number of elements with certain properties inside 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...
]}

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]++
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

Take a look fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...