Based on GPT Answer: Refer to
You can use the array traversal method and object manipulation in JavaScript to achieve this conversion. Here is an example of code that converts a raw array to the target format:
let arr = [
{day:'2021-1-1',day1:'全天',time:'00:00',name:123},
{day:'2021-1-1',day1:'全天',time:'00:00',name:456},
{day:'2021-1-1',day1:'非全天',time:'10:00',name:789},
{day:'2021-1-2',day1:'非全天',time:'10:00',name:777},
{day:'2021-1-2',day1:'非全天',time:'10:00',name:888},
];
let List = [];
// 遍历原始数组,按照日期和时间将数据分类存储
arr.forEach(item => {
let dayItem = List.find(day => day.day === item.day);
if (!dayItem) {
dayItem = { day: item.day, children: [] };
List.push(dayItem);
}
let timeItem = dayItem.children.find(time => time.time === item.day1);
if (!timeItem) {
timeItem = { time: item.day1, children: [] };
dayItem.children.push(timeItem);
}
timeItem.children.push(item);
});
console.log(List);
Explanation:
defines an empty array List to store the converted data.
Traverses the original array arr, for each element:
uses the List.find() method to find if there is already data for that date. If it cannot be found, a new date item is created and added to the List array.
Finds if there is already data for that time in the children subarray for that date. If it cannot be found, a new time item is created and added to children.
Adds the current element to the children subarray of the time item. When the
completes the traversal, the data in the List array has been converted to the target format.
Note: The dates and times in the above code are formatted as strings and should be adjusted to suit your situation. At the same time, the time part needs to be expressed as a string, not a numeric type.