0
Follow
0
View

How does this tree transform?

wangxianchun 注册会员
2023-02-27 18:10

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > you can use the JavaScript in the reduce method was carried out on the original array traversal and transformation. Here is a possible solution:

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.reduce((result, item) => {
  // 根据日期查找是否已经存在该日期的数据
  let date = result.find(date => date.day === item.day);
  if (!date) {
    // 如果不存在,就创建一个新的日期节点
    date = {
      day: item.day,
      children: []
    };
    result.push(date);
  }

  // 根据时间查找是否已经存在该时间段的数据
  let time = date.children.find(time => time.time === item.time);
  if (!time) {
    // 如果不存在,就创建一个新的时间段节点
    time = {
      time: item.time,
      children: []
    };
    date.children.push(time);
  }

  // 将当前的数据节点添加到时间段节点的子节点数组中
  time.children.push({
    day: item.day,
    day1: item.day1,
    time: item.time,
    name: item.name
  });

  return result;
}, []);

console.log(List);


Explain:

  1. uses reduce method to traverse the original array and returns the converted result;
  2. For each array element, first find if the date node already exists, and if it does not, create a new date node;
  3. Finds whether the time period node already exists in the date node, and creates a new time period node if it does not exist;
  4. Adds the current data node to the array of child nodes of the time period node;
  5. Finally returns the transformed array.
dj215421291 注册会员
2023-02-27 18:10
time === item.time) { timeIndex = j; break; } } if (timeIndex === -1) { List[dayIndex].children.push({ time: item.time, children: [] }); timeIndex = List[dayIndex].children.length - 1; } List[dayIndex].children[timeIndex].children.push(item); } .
< !- - - - - >

About the Author

Question Info

Publish Time
2023-02-27 18:10
Update Time
2023-02-27 18:10