今天有个朋友问了我一个需求,她有个数组,需要根据数组中的type字段生成对应type相同的数组,而这个type是前端界面上动态添加获得的,也不曾有码表。
先上数组
var arr = [ {regulationsId: 5172, title: "测试111标题2 ", type: 610, state: 1, createdTime: 1530152467000}, {regulationsId: 5169, title: "测试111标题", type: 610, state: 1, createdTime: 1530085573000}, {regulationsId: 5170, title: "测试123标题", type: 609, state: 1, createdTime: 1530085687000}, {regulationsId: 5171, title: "测试1122标题", type: 608, state: 1, createdTime: 1530085750000} ];
可以发现这个需求就是数组的名称要动态生成,奉上代码如下:
var arr = [ {regulationsId: 5172, title: "测试111标题2 ", type: 610, state: 1, createdTime: 1530152467000}, {regulationsId: 5169, title: "测试111标题", type: 610, state: 1, createdTime: 1530085573000}, {regulationsId: 5170, title: "测试123标题", type: 609, state: 1, createdTime: 1530085687000}, {regulationsId: 5171, title: "测试1122标题", type: 608, state: 1, createdTime: 1530085750000} ]; //先获取一下这个数组中有多少个type var types = []; for(var i in arr){ if(types.indexOf(arr[i].type) === -1){ types.push(arr[i].type) } } //一个包含多个list的结果对象 var obj = {}; // 根据type生成多个数组 for(var k in types){ for(var j in arr){ if(arr[j].type == types[k]){ console.log(types[k], ">>>>>>>>>", arr[j]) obj[types[k]] = obj[types[k]] || []; obj[types[k]].push(arr[j]) } } } console.log(types) console.log(obj)
解决方案如上,应该还有高逼格的实现方法,本人愚钝,暂时想到这个方法。