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",}]}]
2 回答
呼唤远方
TA贡献1856条经验 获得超11个赞
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
TA贡献2036条经验 获得超8个赞
写了一个方法,可能不是最简单的实现方法,仅供参考: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);
添加回答
举报
0/150
提交
取消