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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…