工作中遇到的将json重新构建的例子

来源:互联网 发布:淘宝提交营业执照 编辑:程序博客网 时间:2024/04/30 16:08

有一个json数组是这样的格式:

var machine_list = [{          "error_count": "4",          "ip": "192.168.1.102",          "type": "S100"      },{          "error_count": "2",          "ip": "192.168.1.103",          "type": "S100"      },    {          "error_count": "0",          "ip": "192.168.1.112",          "type": "S200"      },    {    "error_count": "0","ip": "192.168.1.113","type": "S200"    },    {    "error_count": "0","ip": "192.168.1.114","type": "S200E"    }]
这边要将每一种设备类型展示,然后再展示设备类型下面的ip,以及故障数,上面的json格式的数组不太好遍历

下面我的思路是将每个设备类型领出来,作为一个key,这个key对应的value就是这个设备类型下面的ip,这样就好遍历了。页面好展现一点;

整个的代码:

<script type="text/javascript">var machine_list = [{          "error_count": "4",          "ip": "192.168.1.102",          "type": "S100"      },{          "error_count": "2",          "ip": "192.168.1.103",          "type": "S100"      },    {          "error_count": "0",          "ip": "192.168.1.112",          "type": "S200"      },    {    "error_count": "0","ip": "192.168.1.113","type": "S200"    },    {    "error_count": "0","ip": "192.168.1.114","type": "S200E"    }]//重新生成一个json格式的数组:function get_machine_list(json){var machine_list_new=[];var machine_item  = {"machine_type":null,"data":[]};var json_type = [];//将设备type找出来for(var k=0; k<json.length;k++){if(json_type.indexOf(json[k].type) == -1){json_type.push(json[k].type);}}console.log(json_type);for(var j=0; j<json_type.length; j++){var type = json_type[j];//拿出每一个设备类型for(var i=0; i<json.length; i++){if(json[i].type == type){machine_item.machine_type = type;machine_item.data.push(json[i]);}}machine_list_new.push(machine_item);machine_item = {"machine_type":null,"data":[]}}return machine_list_new;}var machinelist_new = get_machine_list(machine_list);console.log(machinelist_new);<span style="font-family: Arial, Helvetica, sans-serif;"></script></span>


重新生成的json格式的数组:



心得:

1、indexOf()用法:

可以用数组的indexOf函数,方法arr.indexOf(find,start);

find:要找的内容,必须;

start:查找开始下标,可选;

返回:查找数据所在的下标,如果没找到,返回-1

如果只要知道是否有8这个数字,直接调用arr.indexOf(8),如果返回值不为-1,说明找到了

var s=[1,2,3,5,6,9];var u=s.indexOf(5);//返回5所在的下标3var d=s.indexOf(8);//返回-1

2、复杂问题都是简单的组成的。先写简单的,比如先显示S100设备类型下的所有ip,再想办法循环,显示所有设备类型下面的ip




0 0