vararr=[{name:'color',value:'red',position:1},{name:'size',value:'s',position:2},{name:'price',value:20,position:3}]varlist=[{id:11,color:'red'},{id:12,size:'s'},{id:13,price:200},{id:14,size:'m'},{id:15,color:'pink'},{id:16,price:10},]position:1,代表字段option1,position:2,代表字段option2,position:3,代表字段option3,如何把list转成list=[{id:11,option1:'red'},{id:12,option2:'s'},{id:13,option3:200},{id:14,option2:'m'},{id:15,option1:'pink'},{id:16,option3:10},]虽然小问题,但是想不到好方法去转换.这是一时乱写的,知道是错的,但没有其他思路。请大家帮忙看看list.forEach((item,index)=>{if(item.option1==undefined||item.option2==undefined||item.option3==undefined){list.forEach((sub,subindex)=>{if(sub.name=="color"&&item.color!==undefined){item["option"+(subindex+1)]=item.color;}if(sub.name=="size"&&item.size!==undefined){item["option"+(subindex+1)]=item.size;}if(sub.name=="price"&&item.price!==undefined){item["option"+(subindex+1)]=item.price;}});}});
2 回答
千巷猫影
TA贡献1829条经验 获得超7个赞
list.map(item=>{const{id}=itemconst[_,key]=Object.keys(item)constvalue=item[key]letobj={id}const{position}=arr.find(({name})=>name===key)||{}if(position){obj[`option${position}`]=value}returnobj})
PIPIONE
TA贡献1829条经验 获得超9个赞
for(vari=0;ivarkey,value,position,a=list[i]; for(var_keyina){if(_key!=="id"){key=_key;value=a[_key];deletea[_key];break;}}for(varj=0;jvarb=arr[j]; varname=b.name;if(name===key){position=b.position;break;}}a["option"+position]=value;}console.log(list);
添加回答
举报
0/150
提交
取消