You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
846 B

  1. export function arrayToTreeByLevelCode(data, levelField, childrenField) {
  2. if (!Array.isArray(data)) {
  3. console.error("Invalid data: data is not an array", data);
  4. return [];
  5. }
  6. const tree = [];
  7. const map = new Map();
  8. // 初始化 Map,每个 levelCode 对应一个节点对象
  9. data.forEach(item => {
  10. map.set(item[levelField], { ...item, [childrenField]: [] });
  11. });
  12. data.forEach(item => {
  13. const node = map.get(item[levelField]);
  14. const parentKey = item[levelField].split('.').slice(0, -1).join('.'); // 获取父节点的 levelCode
  15. if (parentKey && map.has(parentKey)) {
  16. // 如果有父节点,添加到父节点的 children 数组中
  17. map.get(parentKey)[childrenField].push(node);
  18. } else {
  19. // 没有父节点,说明是根节点
  20. tree.push(node);
  21. }
  22. });
  23. return tree;
  24. }