我想要返回每个属性的计数。例如,我想返回每组中有多少人。因此,对于以下JSON,它将返回组1中的3个人,组3中的3个人,组16中的2个人等。
我正在寻找一个Javascript或jQuery解决方案。感谢。
任何帮助将不胜感激。
注意:我不需要帮助解析JSON。我只需要帮助找到每次事件的计数。
{
"people":[
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
]
}
答案 0 :(得分:3)
var obj = {
"people": [
{"id":"0","name":"Mike Johnson","group":1},
{"id":"1","name":"Bob Smith","group":2},
{"id":"2","name":"Richard Thomas","group":3},
{"id":"3","name":"Betty White","group":16},
{"id":"4","name":"Tim Thompson","group":3},
{"id":"5","name":"Carl Lewis","group":16},
{"id":"6","name":"Kathy Towers","group":3},
{"id":"7","name":"Billy Bob","group":1},
{"id":"8","name":"Sally Bailey","group":1}
]
};
function getCount(group) {
var count = 0;
for (var i = 0; i < obj.people.length; i++) {
if (obj.people[i].group == group) {
count++;
}
}
return count;
}
getCount(1); // should return 3
如果obj
不是全局的,您可以将其传递给函数,它将是这样的:
function getCount(arr, group) {
var count = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].group == group) {
count++;
}
}
return count;
}
getCount(obj.people, 1); // should return 3
答案 1 :(得分:1)
您可以使用以下内容提取组:
> var groups = foo['people'].map(function(value, index) {return value['group']});
[1, 2, 3, 16, 3, 16, 3, 1, 1]
从那里,只需使用这些键创建一个对象:
var group_count = {};
groups.forEach(function(value, index) {
if (value in group_count) {
group_count[value] += 1;
} else {
group_count[value] = 1;
}
});
这将为您提供一个对象,其中包含每个组的出现次数。
此外,此代码无法使用IE8及更低版本,因此您必须在网络上的某处找到forEach
和map
polyfill。