在线等!现在有如下数组,我要把数组的格式改变成如下这个,如何实现呢?

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},
]
}];
这个怎么实现呢?
蓝山帝景
浏览 321回答 2
2回答

临摹微笑

functiontransform(arr){varret=[];if(Array.isArray(arr)&&arr.length){loop:for(vari=0;i

阿波罗的战车

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})})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript