编程技术

JavaScript遍历JSON数据

获取的JSON数据如下:


{
    "code": 200,
    "message": "操作成功!",
    "nowPage": 1,
    "pageSize": 3,
    "rows": [
        {
            "id": 2,
            "phone": "222222",
            "nickname": "大米",
            "baoXiuQuYu": "个人住宅",
            "state": 1,
            "bxTime": "2016-12-12 00:00:00",
            "bxContent": "222"
        },
        {
            "id": 4,
            "phone": "44444",
            "nickname": "兰欣",
            "baoXiuQuYu": "个人住宅",
            "state": 1,
            "bxTime": "2016-12-05 00:00:00",
            "bxContent": "444"
        },
        {
            "id": 1,
            "phone": "111111",
            "nickname": "小米",
            "baoXiuQuYu": "个人住宅",
            "state": 1,
            "bxTime": "2016-12-04 00:00:00",
            "bxContent": "1111"
        }
    ],
    "total": 4,
    "totalPage": 2
}

由于项目中需要得到某个状态值,例如state,遍历得到他的总数:


console.log(JSON.stringify(data.rows));//控制台输出json
        var objs = eval(data.rows);
        console.log("遍历JSON数据几条:"+objs.length);
        var stuNum = 0;
        for(var i = 0; i < objs.length; i++) {
            console.log("获取状态值:"+objs[i].state);
            if (objs[i].state == 2 ) {
                stuNum ++;
                console.log("状态值为1的一共有:"+stuNum);
            }
        }
        console.log("总数:"+stuNum);

关于eval()解释:3wschool

本站内容遵循知识共享署名-非商业性使用-相同方式共享4.0 国际许可协议

转载原创文章请注明转自:JavaScript遍历JSON数据

发表评论

理性发言,共建美好精神家园!