当前位置: 代码迷 >> Web开发 >> 计算JSON某个数据的数量,该怎么处理
  详细解决方案

计算JSON某个数据的数量,该怎么处理

热度:75   发布时间:2012-12-29 10:28:09.0
计算JSON某个数据的数量

[
{"id": 123, "type": "1"},
{"id": 234, "type": "1"},
{"id": 345, "type": "2"},
{"id": 4646, "type": "2"},
{"id": 878, "type": "2"},
{"id": 78987, "type": "2"},
{"id": 4646, "type": "3"},
{"id": 4646, "type": "3"},
{"id": 4646, "type": "3"},
{"id": 4646, "type": "3"},
{"id": 4646, "type": "3"},
]


例如 怎么计算type=2有多少个

还有个问题怎么现在每天回贴都没分了。。。。
------解决方案--------------------
var arr = [
    {"id": 123, "type": "1"},
    {"id": 234, "type": "1"},
    {"id": 345, "type": "2"},
    {"id": 4646, "type": "2"},
    {"id": 878, "type": "2"},
    {"id": 78987, "type": "2"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
];

var count = 0;
for(var i = 0 ; i < arr.length ; i ++)
{
    if(arr[i].type == '2') count ++
}
alert(count)

------解决方案--------------------

var json = [
    {"id": 123, "type": "1"},
    {"id": 234, "type": "1"},
    {"id": 345, "type": "2"},
    {"id": 4646, "type": "2"},
    {"id": 878, "type": "2"},
    {"id": 78987, "type": "2"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
    {"id": 4646, "type": "3"},
];
var count = 0;
for(var i=0;i<json.length;i++){
  count += json[i].type=="2"?1:0;
}
alert(count);

------解决方案--------------------

Array.prototype.FindAll = function(fn){
if(typeof(fn) === 'function'){
ret = [];
for(var i = 0, l = this.length; i<l; i++){
var o = this[i];
if(fn(o)) ret[ret.length] = o;
}
return ret;
}
return null;
}
var arr = 上面定义的那些数据;
alert(arr.FindAll(function(o){return o.type == "1";}).length);