let list =[{name:"张三",gender:"张",age:"20"},{name:"李四",gender:"李",age:"25"},{name:"王五",gender:"王",age:"30"},{name:"张飞",gender:"张",age:"20"},{name:"李红",gender:"李",age:"22"}]
2.合并后数组:
let list =[{gender:"张",{name:"张三",gender:"张",age:"20"},{name:"张飞",gender:"张",age:"20"}},{gender:"李",{name:"李四",gender:"李",age:"25"},{name:"李红",gender:"李",age:"22"}},{gender:"王",{name:"王五",gender:"王",age:"30"},}]
3.实现方法一:
let tempArr =[];
let Data =[];for(let i =0; i < list.length; i++){if(tempArr.indexOf(list[i].gender)===-1){Data.push({gender: list[i].gender,dataInfo:[list[i]]});tempArr.push(list[i].gender);}else{for(let j =0; j < Data.length; j++){if(Data[j].gender== list[i].gender){Data[j].dataInfo.push(list[i]);break;}}}}console.log(Data);
测试:
4.实现方法二:
let dataInfo ={};
list.forEach((item, index)=>{let { gender }= item;if(!dataInfo[gender]){dataInfo[gender]={gender, child:[]}}dataInfo[gender].child.push(item);});
let newList = Object.values(dataInfo);// list 转换成功的数据
console.log(newList)