在线等!请教,如何把如下格式进行整合

[
{time:12/30/2018,cabin:'w',Type:'NonStop',dcp:37},
{time:12/30/2018,cabin:'w',Type:'NonStop',dcp:37},
{time:12/31/2018,cabin:'a',Type:'NonStop',dcp:37},
{time:12/31/2018,cabin:'w',Type:'NonStop',dcp:37},
{time:12/31/2018,cabin:'w',Type:'NonStop',dcp:37},
{time:12/30/2017,cabin:'w',Type:'NonStop',dcp:37},
{time:12/31/2017,cabin:'w',Type:'NonStop',dcp:37},
{time:12/31/2017,cabin:'w',Type:'NonStop',dcp:37},
{time:12/31/2017,cabin:'w',Type:'NonStop',dcp:37},
{time:12/31/2017,cabin:'j',Type:'NonStop',dcp:37},
]
[
{time:12/30/2018,cabin:'w',Type:'NonStop',dcp:74,w:2},
{time:12/31/2018,cabin:'w',Type:'NonStop',dcp:74,w:2},
{time:12/31/2018,cabin:'a',Type:'NonStop',dcp:37,a:1},
{time:12/31/2017,cabin:'w',Type:'NonStop',dcp:111,w:3},
{time:12/31/2017,cabin:'j',Type:'NonStop',dcp:37,j:1},
]
请问各位大佬,如何把上面的数组整合成下面的数组形式啊,
只要是日期相同,cabin相同,那么他们的其他字段的数值就相加,
并且把cabin字段的value取出来变为一个新的字段加入当前对象,
而它的值则是重复的数量,就是同一日期同一个cabin的数量
ibeautiful
浏览 226回答 2
2回答

忽然笑

constresData=sourceData.reduce((prev,cur,index,src)=>{if(!index)return[{...cur,[cur.cabin]:1}]constprevEle=prev[prev.length-1]if(cur.time===prevEle.time&&cur.cabin===prevEle.cabin){prevEle[prevEle.cabin]++prevEle.dcp+=cur.dcp}else{prev.push({...cur,[cur.cabin]:1})}returnprev},[])

慕丝7291255

constnewArr=arr.reduce((a,b)=>{let{time,cabin,dcp}=b;letindex=a.findIndex(val=>{returnval.time===time&&val.cabin===cabin;});if(index>=0){letcur=a[index];cur[cabin]++;cur['dcp']+=dcp;}else{letclone={...b};clone[cabin]=1;a.push(clone);}returna;},[]);时间格式被转换了,需要自行调整下
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript