Moh*_*hit 7 javascript arrays jquery json
我有一些JSON数据:
{"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...
]}
Run Code Online (Sandbox Code Playgroud)
我希望能够计算所有有2根头发,3根头发等的人.现在我正在使用jQuery.each()加上递增计数数组,它工作正常.但我想知道是否有更简单的方法来做到这一点.
更新:附加代码说明我现在在做什么:
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]++
}
});
Run Code Online (Sandbox Code Playgroud)
您可以使用该filter函数来过滤对象数组:
var data = {...}
data.humans.filter(function(o) { return o.hairs == 2 }).length
//Return the number of humans who have 2 hairs
Run Code Online (Sandbox Code Playgroud)
看看小提琴
| 归档时间: |
|
| 查看次数: |
2214 次 |
| 最近记录: |