为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蓝山帝景 2019-08-13 23:55:50
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));
                            
查看完整回答
反对 回复 2019-08-13
?
阿波罗的战车

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
})
})
                            
查看完整回答
反对 回复 2019-08-13
  • 2 回答
  • 0 关注
  • 320 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信