请各位大佬指点!js 根据日期 对数组重新分组各位有什么建议?

原数据:
vardata=[
{"name":"小明","age":"4","birthday":"5-1"},
{"name":"小黄","age":"4","birthday":"5-1"},
{"name":"小红","age":"4","birthday":"5-3"},
]
希望整理后得到:
varnewArr=[
{
"birthday":"5-1",
"detailList":"[{'name':'小明','age':'4'},{'name':'小黄','age':'4'}]"
},
{
"birthday":"5-3",
"detailList":"[{'name':'小红','age':'4'}]"
}
];
我的思路;data数组第0项直接push(birthday+detailList)整个到新数组newArr,但从第1项就要开始去newArr比较birthday,如果birthday相同,就只用push(detailList),如果不同就push{birthday+detailList}
遇到问题:重复打印了一些数据
我的代码:`vardata=[
{"name":"小明","age":"4","birthday":"5-1"},
{"name":"小黄","age":"4","birthday":"5-1"},
{"name":"小红","age":"4","birthday":"5-3"},
]
//[希望得到]
//varnewArr=[
//{
//"birthday":"5-1",
//"detailList":"[{'name':'小明','age':'4'},{'name':'小黄','age':'4'}]"
//},
//{
//"birthday":"5-3",
//"detailList":"[{'name':'小红','age':'4'}]"
//}
//];
vararr=[];//存放新数组
for(vari=0;i//读取每条数据的日期
varresBirthday=data[i].birthday;
//当日期相同,只要传这个
varvalDetailList={
"name":data[i].name,
"age":data[i].age
}
//当日期没有相同的,就新建一个Item
varvalItem={
"birthday":'',
"detailList":[]
}
valItem.birthday=resBirthday;
valItem.detailList.push(valDetailList);
//第0个不需要比较
if(i==0){
arr.push(valItem);
}
//第1个就要开始找新数组arr相同的日期
else{
for(vark=0;kif(resBirthday==arr[k].birthday){
arr[k].detailList.push(valDetailList);
}
else{
arr.push(valItem);
}
}
}
}
console.log(arr);`
UYOU
浏览 190回答 2
2回答

至尊宝的传说

下面这段代码修改如下://第1个就要开始找新数组arr相同的日期else{varindex=-1;//通过for循环查找indexfor(vark=0;k
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript