读取API后,数组多是以字符串对象的形态存在于数组中的。根据实际情况,需要对得到的数据进行分组、过滤和筛选。
如下,通过api获取以下格式数组,可以理解为从mysql数据库读取的二维数组:
var arr = [ {area_name: "A街道", health_id: "1", health_must: "1693", health_today: "8", checked: "1"}, {area_name: "B镇", health_id: "2", health_must: "1771", health_today: "2", checked: "1"}, {area_name: "C镇", health_id: "3", health_must: "1456", health_today: "0", checked: "1"}, {area_name: "D镇", health_id: "4", health_must: "1458", health_today: "65", checked: "1"}, {area_name: "E街道", health_id: "5", health_must: "1544", health_today: "2", checked: "1"}, {area_name: "F街道", health_id: "6", health_must: "1597", health_today: "401", checked: "1"}, {area_name: "H街道", health_id: "2", health_must: "1481", health_today: "7", checked: "1"}, {area_name: "I镇", health_id: "6", health_must: "1315", health_today: "2", checked: "1"}, {area_name: "J镇", health_id: "4", health_must: "1660", health_today: "2", checked: "0"}, {area_name: "K街道", health_id: "4", health_must: "2240", health_today: "8", checked: "0"}, {area_name: "L镇", health_id: "3", health_must: "1511", health_today: "8", checked: "0"}, {area_name: "M街道", health_id: "1", health_must: "1840", health_today: "2", checked: "0"}, {area_name: "N街道", health_id: "1", health_must: "1738", health_today: "347", checked: "0"}, {area_name: "P街道", health_id: "1", health_must: "1512", health_today: "2", checked: "0"} ];
根据项目需求,我们需要提供以下数据处理结果:
1、获取health_id为指定的数据,如:health_id=1的数据数组;
2、获取多个health_id为指定的数据,如health_id=1,health_id=3,health_id=4……的数据分组数据;
3、获取health_id且(或)checked同时满足的逻辑条件数据,如health_id=1且checked=0;
这些在SQL语句中都有固定的语法,直接调用即可,那么如何在数组中实现以上的需求呢?
解决方案如下:
1.单条件单数据筛选:
/*1.单条件单数据筛选 *filte数组过滤,指定对象字段的的筛选方式 * arr,包含对象的数组; * health_id,对象数组对应的键; */ function filterByName(arr, health_id) { return arr.filter(item => item.health_id == health_id); } //获取health_id=4的数组数据; var a = filterByName(arr, "4"); console.log(a);
返回结果:
2.单条件多数据筛选后并自动分组
/*2.单条件单数据筛选后,并自动分组 *filte数组过滤,指定对象字段的的筛选方式 * arr,包含对象的数组; * health_id,对象数组对应的键; */ function filterByPolyName(arr, nameArr) { var result=[]; for(var i = 0; i < nameArr.length; i++) { result.push(arr.filter(item => item.health_id === nameArr[i])); } return result; } //获取health_id=1和3的数组数据; var b = filterByPolyName(arr,['1','3']); console.log(b);
返回结果:
3、逻辑条件筛选
/*3.逻辑条件筛选,多条件多数据筛选 *filte数组过滤,指定对象字段的的筛选方式 * arr,包含对象的数组; * health_id,对象数组对应的键; * 根据id且checked筛选; */ function filterByName2(aim, health_id, checked) { return aim.filter(item => item.health_id === health_id && item.checked === checked); } //health_id=1且checked=0筛选 var c = filterByName2(arr,"1","0"); console.log(c);
返回结果:
Done!