I want to return the count of each property. For example, I would like to return how many people are in each group. So for the following JSON, it would return 3 people in Group 1, 3 people in Group 3, 2 people in Group 16, etc.
I'm looking for a Javascript or jQuery solution.
Note: I do not need help parsing the JSON. I only need help in finding the counts of each occurrence.
{
"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}
]
}
Like some comment said, you have to loop through the "people" array. It's easy to turn this "feature" into a function like I have so you can just specify the group you're searching for, and get back the number of people.
http://jsfiddle.net/UdhRW/
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
If obj isn't global, you can pass it to the function and it would be like this:
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
You can extract the groups by using something like this:
> var groups = foo['people'].map(function(value, index) {return value['group']});
[1, 2, 3, 16, 3, 16, 3, 1, 1]
From there, just create an object with these keys:
var group_count = {};
groups.forEach(function(value, index) {
if (value in group_count) {
group_count[value] += 1;
} else {
group_count[value] = 1;
}
});
This will give you an object that contains the number of occurrences of each group.
Also, this code won't work IE8 and lower, so you'll have to find a forEach and map polyfill somewhere on the web.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With