有一个原始数组格式如下[{Voltage:[{value:"-",timestamp:1551082567000,status:-2}{value:125,timestamp:1551082321000,status:1}{value:123,timestamp:1551082251000,status:1}]},{Ammeter:[{value:20,timestamp:1551082567000,status:-2}{value:15,timestamp:1551082321000,status:1}{value:13,timestamp:1551082251000,status:1}]}]Voltage和Ammeter名称都是动态改变的。请问一下如何才能使这个数组转换成以下格式?[{Voltage:'-',Ammeter:20,timestamp:1551082567000,Voltage_status:-2,Ammeter_status:-2},{Voltage:125,Ammeter:15,timestamp:1551082321000,Voltage_status:1,Ammeter_status:1},{Voltage:123,Ammeter:13,timestamp:1551082251000,Voltage_status:1,Ammeter_status:1}]谢谢大家不吝赐教!
2 回答
繁星coding
TA贡献1797条经验 获得超4个赞
functiontransformData(original){constmapOriginal=original.map(item=>Object.keys(item).map(category=>item[category].map(categoryData=>({...categoryData,[category]:categoryData.value,[`${category}_status`]:categoryData.status,})))).reduce((a,b)=>(a.reduce((p,n)=>p.concat(n))).concat((b.reduce((p,n)=>p.concat(n)))))constobj={}mapOriginal.forEach(d=>{if(!obj[d.timestamp]){obj[d.timestamp]=d}Object.assign(obj[d.timestamp],d)})returnObject.values(obj).map(item=>{deleteitem['value']deleteitem['status']returnitem})}
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
这种处理,在后台用数据库做可能很简单,就是个join的问题,非要在前端做就麻烦了。timestamp作为key。用一个map给Ammeter数组建索引,然后扫描Voltage数组生成结果,typescript这样写:letm:Map=newMap(); //扫描Ammeter数组for(letaofd[1].Ammeter){m.set(a.timestamp,a);}//扫描Voltageletret:Array=[]; for(letvofd[0].Voltage){lets:number=v.timestamp;leta=m.get(s);letitem={Voltage:v.value,...};if(a){item['Ammeter']=a.value;...//其他的Ammeter属性}ret.push(item);}
添加回答
举报
0/150
提交
取消