推广小程序前端代码
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.

42 lines
962 B

2 months ago
  1. export function handleTree(data, id, parentId, children) {
  2. let config = {
  3. id: id || 'id',
  4. parentId: parentId || 'parentId',
  5. childrenList: children || 'children'
  6. };
  7. var childrenListMap = {};
  8. var nodeIds = {};
  9. var tree = [];
  10. for (let d of data) {
  11. let parentId = d[config.parentId];
  12. if (childrenListMap[parentId] == null) {
  13. childrenListMap[parentId] = [];
  14. }
  15. nodeIds[d[config.id]] = d;
  16. childrenListMap[parentId].push(d);
  17. }
  18. for (let d of data) {
  19. let parentId = d[config.parentId];
  20. if (nodeIds[parentId] == null) {
  21. tree.push(d);
  22. }
  23. }
  24. for (let t of tree) {
  25. adaptToChildrenList(t);
  26. }
  27. function adaptToChildrenList(o) {
  28. if (childrenListMap[o[config.id]] !== null) {
  29. o[config.childrenList] = childrenListMap[o[config.id]];
  30. }
  31. if (o[config.childrenList]) {
  32. for (let c of o[config.childrenList]) {
  33. adaptToChildrenList(c);
  34. }
  35. }
  36. }
  37. return tree;
  38. }