原数据:
var data = [
{"name": "小明","age": "4","birthday": "5-1"},
{"name": "小黄","age": "4","birthday": "5-1"},
{"name": "小红","age": "4","birthday": "5-3"},
]
希望整理后得到:
var newArr = [
{
"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 }
遇到问题:重复打印了一些数据
我的代码:`var data = [
{"name": "小明","age": "4","birthday": "5-1"},
{"name": "小黄","age": "4","birthday": "5-1"},
{"name": "小红","age": "4","birthday": "5-3"},
]
//[希望得到]
// var newArr = [
// {
// "birthday":"5-1",
// "detailList":"[ {'name':'小明','age':'4'} , {'name':'小黄','age':'4'}]"
// },
// {
// "birthday":"5-3",
// "detailList":"[ {'name':'小红','age':'4'}]"
// }
// ];
var arr = []; //存放新数组
for (var i = 0; i < data.length; i++) {
//读取每条数据的日期
var resBirthday = data[i].birthday;
//当日期相同,只要传这个
var valDetailList = {
"name": data[i].name,
"age": data[i].age
}
//当日期没有相同的,就新建一个Item
var valItem = {
"birthday": '',
"detailList": []
}
valItem.birthday = resBirthday;
valItem.detailList.push(valDetailList);
//第0个不需要比较
if (i == 0) {
arr.push(valItem);
}
//第1个就要开始找新数组arr相同的日期
else{
for (var k = 0; k < arr.length; k++) {
if (resBirthday == arr[k].birthday) {
arr[k].detailList.push(valDetailList);
}
else{
arr.push(valItem);
}
}
}
}
console.log(arr);`
下面这段代码修改如下: