需求:
将数据按照日期将原数组合并
源数据:
var arr = [ { createTime: "2022-07-14 ", taskName: "完善个人信息", experiencePoints: '2' }, { createTime: "2022-07-14 ", taskName: "首次下单", experiencePoints: '2' }, { createTime: "2022-07-13 ", taskName: "每日签到", experiencePoints: '2' }, { createTime: "2022-07-14 ", taskName: "每日签到", experiencePoints: '2' }, ]
要转换成的数据:
var arr2 = [ { createTime: "2022-07-14 ", list: [ { taskName: "完善个人信息", experiencePoints: '2' }, { taskName: "首次下单", experiencePoints: '2' }, { taskName: "每日签到", experiencePoints: '2' }, ], }, { createTime: "2022-07-13 ", list: [ { taskName: "每日签到", experiencePoints: '2' }, ], } ]
实现思路:
1.一眼看去,是要按照日期进行数据划分的,那么第一件事就是数组去重,保留不重样的时期
2.接下来就是组装数据了,如果日期相等的话就添加进list
实现代码完整:
var arr = [ //初始代码 { createTime: "2022-07-14 ", taskName: "完善个人信息", experiencePoints: '2' }, { createTime: "2022-07-14 ", taskName: "首次下单", experiencePoints: '2' }, { createTime: "2022-07-13 ", taskName: "每日签到", experiencePoints: '2' }, { createTime: "2022-07-14 ", taskName: "每日签到", experiencePoints: '2' }, ] var arr2 = [ //目标代码 { createTime: "2022-07-14 ", list: [ { taskName: "完善个人信息", experiencePoints: '2' }, { taskName: "首次下单", experiencePoints: '2' }, { taskName: "每日签到", experiencePoints: '2' }, ], }, { createTime: "2022-07-13 ", list: [ { taskName: "每日签到", experiencePoints: '2' }, ], } ] //逻辑部分 let demo3 = [...new Set(arr.map(item => item.createTime))] //['2022-07-14 ', '2022-07-13 '] let end = [] demo3.forEach((i, o) => { end.push({ createTime: i, list: [] }) }) end.forEach((it, id) => { arr.forEach((item, index) => { if (it.createTime == item.createTime) { it.list.push({ taskName: item.taskName, experiencePoints: item.experiencePoints }) } }) }) console.log(end, '------------------------------')