constarr=[{id:1,name:"小明",age:18,dreid:50},{id:2,name:"大热",age:18,dreid:52},{id:4,name:"妇女会计",age:18,dreid:51},{id:3,name:"千万",age:18,dreid:53},{id:1,name:"小强",age:18,dreid:51},{id:3,name:"千的",age:18,dreid:50},{id:2,name:"大巴",age:18,dreid:53},{id:4,name:"妇女放假",age:18,dreid:52},]我要把id相等的放在一个数组,dreid相等的放在一个数组变为这样的,数组的长度是不同id的长度letarr=[{dreid:50,//dreid相等的都放在listDreid数组中listDreid:[{id:1,name:"小明",age:18,dreid:50},{id:3,name:"千的",age:18,dreid:50},],id:1,//id相等的放在listId数组中listId:[{id:1,name:"小明",age:18,dreid:50},{id:1,name:"小强",age:18,dreid:51},]},{dreid:51,//dreid相等的都放在listDreid数组中listDreid:[{id:4,name:"妇女会计",age:18,dreid:51},{id:1,name:"小强",age:18,dreid:51},],id:2,//id相等的放在listId数组中listId:[{id:2,name:"大热",age:18,dreid:52},{id:2,name:"大巴",age:18,dreid:53},]},{dreid:52,//dreid相等的都放在listDreid数组中listDreid:[{id:2,name:"大热",age:18,dreid:52},{id:4,name:"妇女放假",age:18,dreid:52}],id:3,//id相等的放在listId数组中listId:[{id:3,name:"千万",age:18,dreid:53},{id:3,name:"千的",age:18,dreid:50},]},{dreid:53,//dreid相等的都放在listDreid数组中listDreid:[{id:3,name:"千万",age:18,dreid:53},{d:2,name:"大巴",age:18,dreid:53}],id:4,//id相等的放在listId数组中listId:[{id:4,name:"妇女会计",age:18,dreid:51},{id:4,name:"妇女放假",age:18,dreid:52},]}];这个怎么实现呢?
2 回答
临摹微笑
TA贡献1982条经验 获得超2个赞
functiontransform(arr){varret=[];if(Array.isArray(arr)&&arr.length){loop:for(vari=0;ivara=arr[i]; varid=a.id;vardreid=a.dreid;varisFound=0;for(varj=0;jvarb=ret[j]; if(b.id===id){b.listId.push(a);isFound++;}elseif(b.dreid===dreid){b.listDreid.push(a);isFound++}}if(!isFound)ret.push({id:id,listId:[a],dreid:dreid,listDreid:[a]});}}returnret;}console.log(transform(arr));
阿波罗的战车
TA贡献1862条经验 获得超6个赞
letres=[]arr.forEach((item,index)=>{letid=item['id'];letdreid=item['dreid'];letlistId=[]letlistDreid=[]arr.forEach((item1)=>{if(item1['id']==index+1){listId.push(item1)}if(dreid==item1['dreid']){listDreid.push(item1)}})res.push({dreid:dreid,listDreid:listDreid,id:id,listId:listId})})
添加回答
举报
0/150
提交
取消