猿问

社区求助 js 数组组合成需要的新数组

vararr=[
{
"areaName":"北欧",
"countryName":"阿布哈兹",
"packageName":"测试1",
"packagePrice":"1.0",
"mark":0
},
{
"areaName":"西欧",
"countryName":"德国",
"packageName":"测试3",
"packagePrice":"14.0",
"mark":1
},
{
"areaName":"北欧",
"countryName":"丹麦",
"packageName":"测试2",
"packagePrice":"14.0",
"mark":0
}
]
需要的新数组格式为
vararr2=[
{
"areaName":"北欧",
"mark":0,
"list":[
{
"countryName":"阿布哈兹",
"packageName":"测试1",
"packagePrice":"1.0",
},{
"countryName":"丹麦",
"packageName":"测试2",
"packagePrice":"14.0",
}
]
},
{
"areaName":"西欧",
"mark":1,
"list":[
{
"countryName":"德国",
"packageName":"测试3",
"packagePrice":"14.0",
}
]
}
]
紫衣仙女
浏览 335回答 2
2回答

呼唤远方

functiontransform(arr){constobj={}arr.forEach(item=>{const{mark,areaName,...rest}=itemif(!obj[item.mark]){obj[mark]={mark,areaName,list:[rest],}}else{obj[mark].list.push(rest)}})returnObject.values(obj)}

慕桂英3389331

写了一个方法,可能不是最简单的实现方法,仅供参考:letarr=[];//这里是你上面的数据lettemp_obj={};arr.map(item=>{letbuff_property="mark"+item.mark;if(temp_obj[buff_property]){temp_obj[buff_property].list.push({"countryName":item.countryName,"packageName":item.packageName,"packagePrice":item.packagePrice})}else{temp_obj[buff_property]={"areaName":item.areaName,"mark":item.mark,"list":[{"countryName":item.countryName,"packageName":item.packageName,"packagePrice":item.packagePrice}]}}returnitem;})letarr2=Object.values(temp_obj);temp_obj=null;//使用完成,释放内存console.log(arr2);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答