How does this structure transform?

dzh171 注册会员
2023-02-27 19:13

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 = [

let List = [];

// 遍历原始数组,按照日期和时间将数据分类存储
arr.forEach(item => {
  let dayItem = List.find(day => day.day === item.day);
  if (!dayItem) {
    dayItem = { day: item.day, children: [] };
  let timeItem = dayItem.children.find(time => time.time === item.day1);
  if (!timeItem) {
    timeItem = { time: item.day1, children: [] };



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.

About the Author

Question Info

Publish Time
2023-02-27 19:13
Update Time
2023-02-27 19:13