今天有個朋友問了我一個需求,她有個數組,需要根據數組中的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)
解決方案如上,應該還有高逼格的實現方法,本人愚鈍,暫時想到這個方法。