4

我想返回每个属性的计数。例如,我想返回每个组中有多少人。因此,对于以下 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}
    ]
}
4

2 回答 2

4

就像一些评论说的那样,你必须遍历“人”数组。很容易将这个“功能”变成像我这样的功能,这样您就可以指定您正在搜索的组,并返回人数。

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

如果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
于 2012-10-03T15:48:50.283 回答
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 及更低版本,因此您必须在网络上的某处找到 aforEachmappolyfill。

于 2012-10-03T15:51:35.043 回答