首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web开发 >

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

2012-12-29 
计算JSON某个数据的数量[{id: 123, type: 1},{id: 234, type: 1},{id: 345, type: 2},{

计算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);

热点排行